[英]Webpack is importing modules from my machine's global `node_modules`. How do I get it to only import from my project's `node_modules`?
[英]How do node_modules packages read config files in the project root?
我正在创建一个 npm package 需要能够从项目根目录读取配置文件。 我不知道该怎么做。
例如,
./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
的文件中读取配置。
当我制作第一个npm
package 时遇到了这个问题findup-sync
库很好地解决了这个问题:
const findup = require('findup-sync');
const filePath = findup('filename');
它们从文件所在的目录开始,并在文件系统树中递归地向上查找,直到找到它要查找的文件。
像这样的东西:
const FILE_NAME = 'target-file.json';
const fsp = require('fs').promises,
path = require('path');
let find = async (dir=__dirname) => {
let ls = await fsp.readdir(dir);
if(ls.includes(FILE_NAME))
return path.join(dir,FILE_NAME);
else if(dir == '/')
throw new Error(`Could not find ${FILE_NAME}`);
else
return find(path.resolve(dir,'..'));
}
或者,如果您正在寻找一个标准节点“项目根”,您可能想要递归并找到一个包含目录名称“node_modules”的目录,如下所示:
const fsp = require('fs').promises,
path = require('path');
let find = async (dir=__dirname) => {
let ls = await fsp.readdir(dir);
if(ls.includes('node_modules'))
return dir;
else if(dir == '/')
throw new Error(`Could not find project root`);
else
return find(path.resolve(dir,'..'));
}
有多种方法可以做到这一点。 我创建了一个test-package和一个演示项目node-package-test来测试它。
为了方便参考,请在此处提供主要代码:
project-main\node_modules\test-package\index.js :
const path = require('path');
const fs = require('fs');
const CONFIG_NAME = 'cfg.json';
function init(rootDir = null) {
console.log(`test-package: process.cwd(): ${process.cwd()}`);
console.log(`test-package: path.resolve('./'): ${path.resolve('./')}`);
if (!rootDir) {
//rootDir = path.resolve('./');
// OR
rootDir = process.cwd();
}
//const configPath = path.resolve('./', CONFIG_NAME);
// OR
const configPath = path.join(rootDir, CONFIG_NAME);
if (fs.existsSync(configPath)) {
console.log(`test-package: Reading config from: ${configPath}`);
try {
//const data = fs.readFileSync(configPath, 'utf8');
//const config = JSON.parse(data);
// OR
const config = require(configPath);
console.log(config);
} catch (err) {
console.error(err)
}
} else {
console.log(`test-package: Couldn't find config file ${configPath}. Using default.`)
}
console.log('\n')
}
//init()
const features = {
init: init,
message: `Hello from test-package! 👋`
}
module.exports = features;
项目主\ main.js :
const utils = require('@onkarruikar/test-package')
utils.init();
// OR use
//utils.init('/path/to/rootdir');
console.log(`${utils.message}`);
输出:
E:\node-package-test-main>npm install
added 1 package, and audited 2 packages in 4s
found 0 vulnerabilities
E:\node-package-test-main>npm start
> start
> node .
test-package: process.cwd(): E:\node-package-test-main
test-package: path.resolve('./'): E:\node-package-test-main
test-package: Reading config from: E:\node-package-test-main\cfg.json
{ compilerOptions: { allowJs: true, checkJs: true, noEmit: true } }
Hello from test-package! 👋
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.