Module not found error when trying to use a module as a local module

给你一囗甜甜゛ 提交于 2019-12-12 03:39:58

问题


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;

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());

it throws an error saying:

Error: Cannot find module 'greet-module'

What mistake am I making here?


回答1:


modules.export is incorrect. It should be module.exports with an s.

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.

Update:

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.

See here for the code.



来源:https://stackoverflow.com/questions/42430009/module-not-found-error-when-trying-to-use-a-module-as-a-local-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!