[英]node.js local modules :cannot find module error
我正在尝试在我的应用程序中实现本地模块
1.项目根文件夹我创建了一个名为test
的文件夹,其中包含一个名为index.js
的文件
module.exports = {
myFunction:function(){
console.log('ok');
}
}
2.在根文件夹中的package.json
中添加以下内容
"dependencies": {
"test-module": "file:test"
}
3.当我尝试导入var module = require('test-module');
在app.js
我收到这个错误
找不到模块“测试模块”
您可以提供包含包的本地目录的路径
{
"name": "baz",
"dependencies": {
"bar": "file:../foo/bar"
}
}
并执行npm install -s或npm install --save参考
确保您的test
文件夹有package.json
。
test/package.json
应该有一个值为"test-module"
的"name"
字段(即,与根package.json
的依赖项相同的名称。
我的文件:
test/package.json
{
"name": "test-module",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
test/index.js
module.exports = {
t:() => console.log('t')
};
package.json
{
"name": "t",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"test-module": "file:test"
}
}
app.js
t = require('test-module');
t.t();
这对我有用。
要添加@Blaze 答案,如果您按照步骤(本地路径)安装本地模块,它将为您整理 package.json 中的本地依赖项:
npm i ./test --save
这将产生在正确的地方依赖项dependencies
根package.json
:
"test-module": "file:test"
假设test-module
是本地 dep package.json
的名称。
它应该是这样的:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.