简体   繁体   中英

Avoiding relative require paths in Node.js

I prefer to import dependencies without lots of relative filesystem navigation like ../../../foo/bar .

In the front-end I have traditionally used RequireJS to configure a default base path which enables "absolute" pathing eg myapp/foo/bar .

How can I achieve this in Node.js?

What you can do is use require.main.require which would always be the module path of the starting file. See https://nodejs.org/api/modules.html#modules_accessing_the_main_module

This means, that when you run

const x = require.main.require('some/file/path/y')

It would require it based on the base path of your starting file (that was invoked , node app.js meaning the app.js file).

Other options include using process.cwd() to get the starting path of your app, but that would be depending on where you invoke your node process, not the location of the file. Meaning, node app.js would be different than of you would start it one level up, node src/app.js .

Just to add to the other answer, you can put this few lines in your main file:

(function (module) {
  let path = require('path')
  let __require = module.constructor.prototype.require
  let __cpath = __dirname

  module.constructor.prototype.require = function (str) {
    if (str.startsWith('package:')) {
      let package = str.substr(8)
      let p = path.resolve(__dirname, package)

      return __require(p)
    } else {
      return __require(str)
    }
  }
})(module)

It extends your require in such way:

  • if path begins with package: (ie package:src/foo/bar ) it translates it to require('/absolute/path/to/your/app/src/foo/bar') ,
  • if it doesn't start with package: then it behaves like a normal require would.

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