node_modules 包如何读取项目根目录中的配置文件?

Jak*_*ake 5 javascript node.js npm node-modules

我正在创建一个需要能够从项目根目录读取配置文件的 npm 包。我不知道该怎么做。

例如,

  • Next.js 能够从项目根目录中读取./pages/和读取./next.config.js
  • Jest 能够./jest.config.js从项目根目录读取
  • ESLint 能够./.eslintrc.json从项目根目录读取
  • Prettier 能够./.prettierrc.js从项目根目录读取
  • 打字稿能够./tsconfig.json从项目根目录读取
  • Babel 能够./.babelrc从项目根目录读取

我试过查看他们的源代码以了解他们是如何做到的,但项目太大了,我找不到相关部分。

他们是如何做到这一点的?

And*_*rei 4

首先搜索,path.dirname(process.mainModule.filename)然后向上目录树../, ../../, ../../../向上查找,直到找到配置文件。

这是我从 rc ( https://github.com/dominictarr/rc ) 包中窃取的代码,它将从名为 的文件中读取并解析配置.projectrc

const fs = require('fs');
const path = require('path');

// Utils shamefully stolen from
// https://github.com/dominictarr/rc/blob/master/lib/utils.js

find(...args) {
  const rel = path.join.apply(null, [].slice.call(args));
  return findStartingWith(path.dirname(process.mainModule.filename), rel);
}

findStartingWith(start, rel) {
  const file = path.join(start, rel);
  try {
    fs.statSync(file);
    return file;
  } catch (err) {
    // They are equal for root dir
    if (path.dirname(start) !== start) {
      return findStartingWith(path.dirname(start), rel);
    }
  }
}

parse(content) {
  if (/^\s*{/.test(content)) {
    return JSON.parse(content);
  }
  return undefined;
}

file(...args) {
  const nonNullArgs = [].slice.call(args).filter(arg => arg != null);

  // path.join breaks if it's a not a string, so just skip this.
  for (let i = 0; i < nonNullArgs.length; i++) {
    if (typeof nonNullArgs[i] !== 'string') {
      return;
    }
  }

  const file = path.join.apply(null, nonNullArgs);
  try {
    return fs.readFileSync(file, 'utf-8');
  } catch (err) {
    return undefined;
  }
}

json(...args) {
  const content = file.apply(null, args);
  return content ? parse(content) : null;
}

// Find the rc file path
const rcPath = find('.projectrc');
// Or
// const rcPath = find('/.config', '.projectrc');

// Read the contents as json
const rcObject = json(rcPath);
console.log(rcObject);
Run Code Online (Sandbox Code Playgroud)

您还可以使用 rc 包作为依赖项npm i rc,然后在代码中:

var configuration = require('rc')(appname, {
  // Default configuration goes here
  port: 2468
});
Run Code Online (Sandbox Code Playgroud)

这将从名为 的文件中读取配置.${appname}rc