13

There are some npm packages which I would like to install in a Python virtualenv. For example:

Up to now I only found the complicated way to get these installable in a virtualenv: Create a python package for them.

Is there no simpler way to get npm packages installed in a Python virtualenv?

guettli
  • 25,042
  • 81
  • 346
  • 663

3 Answers3

16

You can install NPM packages on your python virtuaenv using nodeenv.

source ./bin/activate
pip install nodeenv
nodeenv -p

To test if works:

npm install -g npm
npm -v

Sources:

https://pypi.org/project/nodeenv/

https://calvinx.com/2013/07/11/python-virtualenv-with-node-environment-via-nodeenv/

Josir
  • 1,282
  • 22
  • 35
  • The only problem I see is that you will need to worry about two lock files, and two package files, is there a way to do a pipenv install that runs post install the npm install to get the packages for node? – ekiim Mar 09 '19 at 21:00
  • This is a great solution. Thank you for it. – NYCeyes Oct 19 '20 at 17:14
11

NPM and pip have nothing to do with each other, so you won't be able to install NPM packages inside a virtualenv.

However: NPM installs packages in ./node_modules.

So if you created a virtualenv and installed npm modules inside it

virtualenv myproj
cd myproj
source bin/activate
npm install pdfjs-dist jquery-ui

you will end up with the node packages in myproj/node_modules, which is as close as it gets to "installing NPM inside virtualenv".

Nils Werner
  • 34,832
  • 7
  • 76
  • 98
  • Exactly this. If your project uses both Javascript and Python, then you need a `virtualenv` environment for python packages and `node_modules` for node modules. – Kos Sep 19 '16 at 08:00
4

As @Josir suggests, I have used nodeenv in the past but I had an issue when I wanted to have the node modules inside the venv folder of the project as explained in this question.

In short putting a package.json in venv results in not being able to use npx ... unless it is run from the venv folder whereas putting package.json in venv/lib and running npm install from there results in being able to use npx ... from any folder in the project.

This is due to the NODE_PATH environment variable being set to <myproject>/venv/lib/node_modules.

I created a script to automate this which in substance does:

python -m venv venv
source venv/bin/activate
pip install requirements.txt
cp package.json venv/lib
cd venv/lib
nodeenv -p
npm install --no-optional
Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75