Use locally installed modules with npm

Dear fellows,

Today, I will explain why and how use locally installed modules.

You must know, there are two ways to install modules with npm : globally and locally.
By globally, I mean the module will be available for your whole machine. Locally, the module is available in your project.

This is how you install a module globally :

 npm install -g webpack  

And this is how you install a module only in the project you are actually browsing :

 npm install --save-dev webpack 

So, why should you not install and use a globally installed module ?
There are severals reasons, but the most relevant is, of course, about sharing your project with other developers. If you need a specific version of Webpack or TypeScript (or whatever) for your project, and you use your globally installed version of this tool, another developer has chances to never make it run easily because he won’t have the good version of the module in the project.

To use a locally installed module, you can’t just run

 webpack 

in your Terminal. You have to tell npm you want to use a local module.

Before that, you also have to know that when you install a module locally with npm, it creates a kind of launch file in node_modules/.bin folder. We will use this, with, for this blog post, webpack-dev-server.

To do that, open the package.json, and locate the « scripts » part.
By default, there is already a « test » line. Add a « start » line, following this :


"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "./node_modules/.bin/webpack-dev-server"
},

Capture d’écran 2016-11-13 à 14.53.05.png

Now, browsing the project’s folder, you can run webpack-dev-server with

 npm start 

Capture d’écran 2016-11-13 à 14.55.45.png

I’ve done several tests, and it seems that if your modules need some dependences and is running locally, npm will use local dependencies.

As usual, if you have any question, do not hesitate !

Publicités

Laisser un commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l'aide de votre compte WordPress.com. Déconnexion / Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion / Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion / Changer )

Photo Google+

Vous commentez à l'aide de votre compte Google+. Déconnexion / Changer )

Connexion à %s