Speeder123
Speeder123

Reputation: 1

Is full path required in imports in node_modules in javascript (react)?

Let say I have a file which exports a const for e.g direction and is used in the app. Is it possible to resolve the import by just using i.e only the folder name and not the filename:

import direction from './direction';

I am aware that normally this would be the way imports are specified but I cannot edit the files as they are part of node_modules:

import direction from './direction/direction'; or import direction from './direction/direction.js';

I have already read React - import a module in node_modules. I currently don't have an exact repro but I have serveral modules installed from a custom registry which depends on each other and are in node_modules. I get an error message saying Module is not installed even though it is. If I manually update the path as shown above with full filename it works. However they are a part of node_modules and not a good idea to edit it.

Any suggestions so that I can fix this so that paths are resolved from just the foldername?

Thank you in advance

Upvotes: 0

Views: 1417

Answers (1)

samanime
samanime

Reputation: 26625

The answer is "kinda, but mostly no."

The "kinda" part comes from the fact that many bundlers or transpilers will let you define "aliases" to shorten the paths. This is specific to the bundlers or transpilers you may be using, and you'd need to ask a specific question for those to get better help with that.

There is also a "kinda" in that any import in the form of ./<name> will actually try to first import ./<name>.js and then ./<name>/index.js in some environments. However, this is mostly thanks to transpilers again. Using modules directly in browsers won't do this, and it is even being phased out of other places (like Node.js), so it isn't really recommended.

And then finally, the "mostly no" comes in that there isn't a direct, native, universal way to shorten something like ./<name>/<name>.js to just ./<name>. Also, if the module lives in node_modules, it should always (outside of bundler-specific aliases) be referred to as <package-name>/path/to/file.js (extension optional in Node.js and most bundlers/transpilers, not in browsers).

Do note that just <package-name> will import the main file from the package, so if the module only has one file, you could use it to shorten like that.

While sometimes annoying, you're better off using fully-qualified path names, especially as things are starting to get more standardized and start deprecating the various shortcuts we've been using up until now (to line up with browsers which don't allow any shortcuts).

Upvotes: 1

Related Questions