Import module from global NPM packages if it cannot find module in local package #54916
Closed
trymeouteh
started this conversation in
Ideas
Replies: 3 comments 6 replies
-
@nodejs/loaders @nodejs/npm |
Beta Was this translation helpful? Give feedback.
2 replies
-
It’s very intentional that you can’t do this; if you import or require something, it’s a dependency, and it must be in a package.json. There’s a deprecated way you can do this for CJS, but it was left out of ESM by design since it’s a massive antipattern. |
Beta Was this translation helpful? Give feedback.
2 replies
-
My workaround to this was a dynamic import with full path: let ramda
try {
ramda = await import('ramda')
} catch(err) {
let npmGlobalPath = `~/.local/share/nvm/${process.version}/lib/node_modules`
ramda = await import(`${npmGlobalPath}/ramda/src/index.js`)
}
console.log(R.add(5, 7)); Not very convenient, but works. |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
To have the ability to install packages globally and to be able to import them into your scripts.
If the module cannot be found in the local package (node_modules directory), then it will see if it can be found in the global packages.
For example, if Ramda was installed as a global package...
And then a script that can use Ramda from the global packages...
A use case for this is using NodeJS as an alternative language to shell languages like Bash or Powershell or even Python to do system tasks but to have the ability to install and access modules globally instead of having a script in your Documents directory and having to also have a ~/Documents/node_modules/ directory just to be able to use a 3rd party package in your simple script.
Beta Was this translation helpful? Give feedback.
All reactions