Accessing development folder as if it is node global folder

93 views Asked by At

I've modules folder which contains my modules for app1 and have another module folder for app2 and so on. I wish to import my modules without passing virtual module paths.

For eg.

c:\Projects\Apps\
    firstApp
      www.js // I wish to import db with require('db')
    Modules
      db
         src/...*.js  // var ext=require('extensions')
         test/...*.js
         index.js
      api
         src/
           *.js  // var ext=require('db'),
                 // var ext=require('extensions'),
         test/
           *.js  // var testApi = require('api')
         index.js
      extensions
         src/...*.js
         test/...*.js
         index.js

Is there any possibilities to use them as if they are installed localy but in different folders. npm link is usable for this?

1

There are 1 answers

0
goenning On

require('...') will look for modules inside node_modules folder or local files when using ./ or ../.

What you can do is create your own require function that will look for local files even when not using relative/absolute file paths.

In your root/entry code, use this:

var projectDirectory = __dirname;
GLOBAL.requirep = function(path) {
  return require(projectDirectory + '/' + path);
}

//at any js file, you can do this:
var db = requirep('db') //will load db/index.js
var api = requirep('api/src/file.js') //will load api/src/file.js

Because it is global, you can access it from wherever you need.