Search code examples
node.jsrequire

How can I make Node.js 'require' absolute? (instead of relative)


I would like to 'require' my files always by the root of my project and not relative to the current module.

For example, if you look at Express.js' app.js line 6, you will see

express = require('../../')

That's really bad, IMO. Imagine I would like to put all my examples closer to the root only by one level. That would be impossible, because I would have to update more than 30 examples and many times within each example. To this:

express = require('../')

My solution would be to have a special case for root based: if a string starts with an $ then it's relative to the root folder of the project.

What can I do?

Update 2

Now I'm using RequireJS which allows you to write in one way and works both on client and on server. RequireJS also allows you to create custom paths.

Update 3

Now I moved to Webpack and Gulp.js and I use enhanced-require to handle modules on the server side. See here for the rationale: http://hackhat.com/p/110/module-loader-webpack-vs-requirejs-vs-browserify/


Solution

  • Here is the actual way I'm doing for more than 6 months. I use a folder named node_modules as my root folder in the project, in this way it will always look for that folder from everywhere I call an absolute require:

    • node_modules
      • myProject
        • index.js I can require("myProject/someFolder/hey.js") instead of require("./someFolder/hey.js")
        • someFolder which contains hey.js

    This is more useful when you are nested into folders and it's a lot less work to change a file location if is set in absolute way. I only use 2 the relative require in my whole app.