node.jsnpmvirtualenvnodeenv

npm install -g while also updating package.json?


Yes, I know, npm install -g isn't supposed to update package.json. But I need something that will have a similar effect.

My problem is as follows: I want to keep everything separate, so I would like to install node, npm, and every package in a virtual environment. I do this by running:

  1. $ python -m venv <venv_name>
  2. $ <venv_name>\scripts\activate
  3. $ pip install nodeenv
  4. $ nodeenv -p

These four steps download nodejs and npm in a virtual environment.

The issue I'm having is that whenever I want to install a nodejs package via npm I have to install it 'globally' in the virtual environment otherwise it doesn't work. To illustrate this, I will show you what happens when I install a package using normally with:

$ npm install express

or

$ npm install nodmeon

This will save nodemon or express in dependencies, however it wont recognize them as commands, for example:

$ nodemon run start will return 'nodemon' is not recognized as an internal or external command

But this wont happen when I install packages with npm install -g. They work just fine when I do that, but the problem is that they wont save in package.json.

What I've been doing is installing things 2 times, one globally and one normally just so it can be saved in package.json.

My question is: Is there anyway for my global installations to be outputted in package.json? Or is there any way you would recommend me to solve this problem?


Solution

  • You can run the packages cli even if it is not installed globally. like nodemon, knex etc.

    if you are using npm, you can use npx

    npx nodemon
    

    if you are using yarn, you can use yarn

    yarn nodemon
    

    https://blog.scottlogic.com/2018/04/05/npx-the-npm-package-runner.html

    npx is a tool for running npm packages that: live inside of a local node_modules folder or are not installed globally.