有什么方法可以 (a) 禁止来自 require
的 Node 应用程序/import
ing 全局安装的 npm 模块,或者 (b) 至少在使用全局安装的模块时输出警告?
原因是:我反复遇到开发人员(包括我自己)在 Node 应用程序中合并模块但未能将其添加到 package.json
的情况。因为它恰好全局安装在他们的机器上,因此本地机器上没有错误;但是在部署到没有全局安装该模块的系统时,它当然会失败。确保所有模块实际上都包含在 package.json
中会很方便。 .
最佳答案
ESLint方式
1) 使用husky模块:npm install husky --save-dev
2) 安装 eslint 和它的 deps (参见下面的 package.json 示例)。
3)示例包.json:
{
"name": "shopping-cart-estimator-test",
"version": "1.0.0",
"description": "",
"scripts": {
"start": "node ports/http.js",
"eslint-check": "./node_modules/eslint/bin/eslint.js .",
"eslint-fix": "./node_modules/eslint/bin/eslint.js . --fix",
"test": "./node_modules/.bin/mocha test --exit"
},
"devDependencies": {
"babel-eslint": "^10.1.0",
"husky": "^4.2.5",
"mocha": "^7.1.2",
"eslint": "^7.0.0",
"eslint-config-import": "^0.13.0",
"eslint-config-standard": "^14.1.1",
"eslint-plugin-import": "^2.20.2",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1"
},
"dependencies": {
"lodash": "^4.17.15"
},
"husky": {
"hooks": {
"pre-commit": "npm run eslint-check && npm test",
"pre-push": "npm run eslint-check && npm test"
}
}
}
4) 创建
.eslintrc.js
带有 import/no-extraneous-dependencies 的文件规则(它需要 eslint-plugin-import ,确保它在 package.json 中):module.exports = {
"extends": "standard",
"parser": "babel-eslint",
"rules": {
"semi": ["error", "always"],
"no-unused-vars": 1,
"spaced-comment": ["warn"],
"no-trailing-spaces": ["warn"],
"comma-dangle": ["error", {
"arrays": "always",
"objects": "always",
"imports": "never",
"exports": "never",
"functions": "never"
}],
"space-before-function-paren": ["error", {
"anonymous": "always",
"named": "never",
"asyncArrow": "always"
}],
"import/no-extraneous-dependencies": ["error", {"packageDir": __dirname}],
},
"overrides": [{
"files": ["spec/tests/*.js", "spec/tests/**/*.js"],
"rules": {
"no-unused-expressions": 0,
"no-unused-vars": 1
}
}]
};
《自定义脚本方式》
1) 使用husky模块:
npm install husky --save-dev
2)在package.json中添加钩子(Hook)到pre-commit,pre-push:
"husky": {
"hooks": {
"pre-commit": "npm test && node scripts/check-deps.js",
"pre-push": "npm test && node scripts/check-deps.js"
}
}
3) 安装dependency-tree :
npm i --save dependency-tree
4) 写
scripts/check-deps.js
将找到外部(非 package.json)依赖项的脚本,如果它们存在,将:console.warn('Found external dependency');
process.exit(-1);
关于node.js - 禁止 Node 应用程序访问全局 npm 模块,或者至少发出警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61542484/