我正在创建一个需要能够从项目根目录读取配置文件的 npm 包。我不知道该怎么做。
例如,
./pages/
和 ./next.config.js
从项目根目录 ./jest.config.js
从项目根目录 ./.eslintrc.json
从项目根目录 ./.prettierrc.js
从项目根目录 ./tsconfig.json
从项目根目录 ./.babelrc
从项目根目录 我试过查看他们的源代码以了解他们是如何做到的,但是项目太大了,我找不到相关部分。
他们如何做到这一点?
最佳答案
首次搜索 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);
你也可以使用 rc 包作为依赖 npm i rc
,然后在您的代码中:var configuration = require('rc')(appname, {
// Default configuration goes here
port: 2468
});
这将从名为 .${appname}rc
的文件中读取配置。 .
关于javascript - node_modules 包如何读取项目根目录下的配置文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56729491/