iam*_*man 8 javascript module node.js npm express
我正在尝试在我的应用程序中实现本地模块
1.项目根文件夹我创建test
了一个名为的文件 夹index.js
module.exports = {
myFunction:function(){
console.log('ok');
}
}
Run Code Online (Sandbox Code Playgroud)
2.package.json
在根文件夹中添加以下内容
"dependencies": {
"test-module": "file:test"
}
Run Code Online (Sandbox Code Playgroud)
3.当我尝试导入 var module = require('test-module');
时app.js
出现此错误
找不到模块“测试模块”
确保您的test
文件夹中有一个package.json
.
test/package.json
应该有一个"name"
带有值的字段"test-module"
(即与 root 中的依赖项名称相同)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"
}
Run Code Online (Sandbox Code Playgroud)
test/index.js
module.exports = {
t:() => console.log('t')
};
Run Code Online (Sandbox Code Playgroud)
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"
}
}
Run Code Online (Sandbox Code Playgroud)
app.js
t = require('test-module');
t.t();
Run Code Online (Sandbox Code Playgroud)
这对我有用。