我正在创建一个npm包,它需要能够从项目根目录读取配置文件。我不知道该如何做。
例如,
- Next.js能够从项目根目录读取
./pages/
和./next.config.js
- Jest能够从项目根目录读取
./jest.config.js
- ESLint能够从项目根读取
./.eslintrc.json
- Prettier能够从项目根目录读取
./.prettierrc.js
- Typescript能够从项目根目录读取
./tsconfig.json
- Babel能够从项目根读取
./.babelrc
我试着看他们的源代码,看看他们是如何做到这一点,但项目是如此之大,我找不到相关的部分。
他们是如何做到这一点的?
4条答案
按热度按时间anauzrmj1#
首先在
path.dirname(process.mainModule.filename)
中搜索,然后向上到目录树../, ../../, ../../../
,依此类推,直到找到配置文件。下面是我使用的从rc(https://github.com/dominictarr/rc)包中偷来的代码,它将从一个名为
.projectrc
的文件中读取和json解析配置:你也可以使用rc包作为一个依赖
npm i rc
,然后在你的代码中:这将从名为
.${appname}rc
的文件中读取配置。balp4ylt2#
我在制作第一个
npm
包时遇到了这个问题,findup-sync
库很好地解决了这个问题:https://www.npmjs.com/package/findup-sync
ipakzgxi3#
它们从文件所在的目录开始,在文件系统树中向上递归查找,直到找到要查找的文件。
大概是这样的:
或者,如果您要查找一个标准节点“project root”,您可能需要向上递归,找到一个包含名为'node_modules'的目录,如下所示:
n6lpvg4x4#
有多种方法可以做到这一点。我已经创建了一个test-package和一个演示项目node-package-test来测试它。
为了便于参考,请在此处提供主要代码:
项目主目录\节点模块\测试包\索引.js:
项目主文件\main.js:
输出: