node icon indicating copy to clipboard operation
node copied to clipboard

Don't resolve symlinks when requiring

Open VanCoding opened this issue 11 years ago • 204 comments

Currently, Node.js resolves symlinks when requiring and then uses the real location of the package/file as its __filename and __dirname instead of the symlinked one.

This is a problem because symlinked modules don't act the same as locally copied modules.

For example:

app
    index.js //require("dep1")
    node_modules
        dep1
            index.js //require("dep2")
        dep2
            index.js //console.log('fun!'):

works, but

app
    index.js //require("dep1")
    node_modules
        dep1 -> ../../dep1
        dep2
            index.js
dep1
    index.js //require("dep2")

does not, because dep1 does not act like it's located in the node_modules directory of module and thus cannot find dep2.

This is especially a problem when one wants to symlink modules that have peer-dependencies.

Therefore, I suggest changing the behavior to no longer resolve symlinks. What do you think?

VanCoding avatar Oct 16 '15 12:10 VanCoding

@isaacs

if it is a goal to have symlinked modules find one another if they are not otherwise dependent on one another (which, again, I am highly skeptical about as being a good idea)

Well, with the growing trend of the monorepo approach and a significant boost to development speed that thought deserves the benefit of the doubt.

molszanski avatar Jul 18 '16 20:07 molszanski

Symlinking can be fixed, and works great :)

ghost avatar Dec 04 '16 15:12 ghost

Since this issue has the discuss label, I thought I could ask here ...

The second best thing to being able to do const WebSocket = require('../vendors/node/node_modules/ws'); (which cannot be done) is having a symlinked node_modules directory like below.

Which version of the behavior would allow the following?

/var/www/project/
├── app
│   └── ws
│       ├── node_modules -> /var/www/project/vendors/node/node_modules
│       └── wsserver.js
└── vendors
    └── node
        ├── node_modules
        └── package.json

majid4466 avatar May 03 '18 13:05 majid4466

@majid4466 symlinking that node_modules dir should work with the current node.

As for the original opening question: dep1 probably shouldn't require dep2, but instead provide a factory that can produce whatever based on dep2. The factory could have a meta data property to declare which other modules the app (or a plugin manager) needs to provide. It's one flavor of dependency injection.

mk-pmb avatar Mar 14 '19 17:03 mk-pmb