npm equivalent of `pip install -r requirements.txt

2019-02-05 20:41发布

问题:

What are the npm equivalent of:

pip freeze > requirements.txt
pip install -r requirements.txt

回答1:

Normally dependencies in a node project are installed via package.json: https://docs.npmjs.com/files/package.json

You install each dependency with npm install --save my-dependency and it will be added to the package.json file. So the next person on the project can install all the dependencies with npm install command on the same folder of package.json.

But in my case i wanted to install global requirements of npm via a text file (similar to pip install -r requirements.txt).

You can do that with:

cat requirements.txt | xargs npm install -g



回答2:

You might want to take a look at the documentation for npm shrinkwrap. It creates an npm-shrinkwrap.json, which will take precedence over any package.json when installing.

Basically, the equivalent is:

npm shrinkwrap
npm install

Edit:

Since v5.0.0, npm now always creates a package-lock.json, with the same format as npm-shrinkwrap.json. There have been other changes since then, not least in the latest v5.6.0. See the package-lock docs.



回答3:

To install npm packages globally from a text file (e.g. npm-requirements.txt) with a format similar to a pip requirement file:

sed 's/#.*//' npm-requirements.txt | xargs npm install -g

This allows comments in the requirements file, just like pip. (source)

A command similar to pip freeze > requirements.txt is:

ls "$(npm root -g)" > npm-requirements.txt

However, this is imperfect because it does not save the version numbers of npm packages.



标签: npm pip