chen
chen

Reputation: 4490

Why does not the global npm package kick in for module dependency?

I have already installed my typescript and ts-node globally.

I have a package.json file like the following, and when I run npm test, everything works (NOTE: as you can see, ts-node and typescript are installed as local modules in this situation)

{
  "name": "two_sum",
  "version": "1.0.0",
  "description": "two sum problem solver",
  "main": "main.js",
  "scripts": {
    "test": "./node_modules/.bin/mocha --compilers ts:ts-node/register ./test/*.spec.ts"
  },
  "devDependencies": {
    "chai": "^4.1.2",
    "mocha": "^4.1.0",
    "ts-node": "^4.1.0",
    "typescript": "^2.6.2"
  }
}

However, if I take two two modules out of the package.json (and delete the two packages from my ./mode_modules), i.e, ts-node and typescript are not installed locally, I got errors like this:

Error: Cannot find module 'typescript'
    at Function.Module._resolveFilename (module.js:470:15)
    ....
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:427:7)
    at startup (bootstrap_node.js:151:9)
    at bootstrap_node.js:542:3
npm ERR! Test failed.  See above for more details.

Here is my question: why would I need to have those two package installed locally? Why can't the global package kick in to resolve the dependency?

Upvotes: 1

Views: 252

Answers (1)

unional
unional

Reputation: 15589

Globally installed packages are not involved in the resolution when your code runs.

This is because the project (denoted by the presence of your package.json) have no knowledge of what has been installed globally.

Globally installed packages ties to the environment, not the project.

If the globally installed packages are used in the resolution, then the project may work in your environment but not others.

So that will make the executability of your project not reliable (or put in another word, coupled or depended on your environment).

Nowadays, install global packages for CLI tools only.

Upvotes: 4

Related Questions