简体   繁体   中英

node.js local modules :cannot find module error

I am trying to implement local modules in my application

1.Project root folder i have created folder named test with a file named index.js

      module.exports  = {

     myFunction:function(){
       console.log('ok');
     }
}

2.Added the following in package.json in the root folder

"dependencies": { 
    "test-module": "file:test"
  }

3.When i try to import var module = require('test-module'); in app.js i got this error

Cannot find module 'test-module'

you can provide a path to a local directory that contains a package

{
  "name": "baz",
  "dependencies": {
    "bar": "file:../foo/bar"
  }
}

and perform or reference参考

Make sure your test folder has a package.json .

test/package.json should have a "name" field with the value "test-module" (ie, same name as the dependency in your root package.json .

My files:

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

This is working for me.

To add on @Blaze answer, if you follow the steps (Local Paths) to install a local module, it will sort out for you the local dependency in your package.json:

npm i ./test --save

That will produce the correct local dependency entry in your dependencies in the root package.json :

"test-module": "file:test"

assuming test-module is the name in the local dep package.json .

This is how it should look like:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM