问题描述
我试图了解如何制作本地模块.在节点应用程序的根目录下,我有一个名为lib
的目录.在lib目录中,我有一个.js
文件,如下所示:
I am trying to understand as how to make a local module. At the root of node application, I have a directory named lib
. Inside the lib directory I have a .js
file which looks like:
var Test = function() {
return {
say : function() {
console.log('Good morning!');
}
}
}();
module.exports = Test;
我用本地模块路径的条目修改了package.json
:
I have modified my package.json
with an entry of the path to the local module:
"dependencies": {
"chat-service": "^0.13.1",
"greet-module": "file:lib/Test"
}
现在,如果我尝试运行类似以下的测试脚本:
Now, if I try to run a test script like:
var greet = require('greet-module');
console.log(greet.say());
它抛出一个错误,说:
Error: Cannot find module 'greet-module'
我在这里犯了什么错误?
What mistake am I making here?
推荐答案
modules.export
不正确.应该是module.exports
和s
.
此外,请确保在添加依赖项后执行npm install
.这会将文件复制到您的node_modules
,并使其对require
功能可用.
Also, make sure after you add the dependency to do an npm install
. This will copy the file over to your node_modules
and make it available to the require
function.
请参阅此处以获得良好参考.
See here for a good reference.
更新:
在通过一些示例弄清楚了这一点后,我注意到,大多数项目的结构都在下面列出.您可能应该将本地模块格式化为它们自己的独立程序包.使用它们自己的文件夹和package.json
文件指定其依赖关系和名称.然后,您可以将其包含在npm install -S lib/test
中.
After going through some examples to figure this out I noticed, most projects have the structure I laid out below. You should probably format your local modules to be their own standalone packages. With their own folders and package.json
files specifying their dependencies and name. Then you can include it with npm install -S lib/test
.
一旦完成,它便对我有用,它将成为一个很好的结构.干杯.
It worked for me once I did it, and it'll be a good structure moving forward. Cheers.
有关代码,请参见此处.
这篇关于尝试将模块用作本地模块时找不到模块错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!