简体   繁体   中英

Writing commonjs module and load it using require (not using relative path)

What is best pratice for referencing a local commonjs module without using a relative path as below?

var custMod= require(‘customModule’);
custMod(true);
custMod.save(‘foo’);

Is there any reference for building a module like this?

If I wrote module like below, getting undefined when I call custMode.save(12);

module.exports = customModule;function customModule(mode) {
  var mode = 1;
  return {
    save: function (value) {
        console.log(mode, value)
    },
    get: function (id) {
        console.log(mode, id)
    }
}

You can add a path for require to check using

require.paths.push('/my/path');

or

require.main.paths.push('/my/path');

Depending on your node version.

Then if customModule.js exists at /my/path/customModule.js , you can just use

require('customModule');

Do note though, you'd need to do this on every module that you intend to use this method on.

I wish node made this easier to be honest. One possibility:

project_root
`--node_modules
   |--npm-module-1
   |--npm-module-2
   |--... (etc)
   `--lib
      |--my-module.js
      `--my-other-module.js

With the above you can then type require('lib/my-module') from anywhere in your project. (Just make sure and never install an npm module named lib :) Another possibility:

project_root
|--node_modules
|  |--npm-module-1
|  |--npm-module-2
|  `--... (etc)
`--lib
   `--node_modules
      |--my-module.js
      `--my-other-module.js

With the above you can then type require('my-module') , but only for any files under project_root/lib/ .

An advantage of the former approach is that require('lib/my-module') makes it super easy at a glance to tell which modules are local to the project. However the latter is less typing.

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