What's the difference between adding Java Script libraries as npm dependencies or simply including them in HTML?

javascript, node.js, npm

Solution

On one hand, `npm` is a Node tool made to install packages for Node. Packages are collections of modules. And in Node, modules are loaded with a `require` call, which is a global function made available by Node.

On the other hand, `<script>` is the basic mechanism used in browsers to load JavaScript code.

This may seem mutually exclusive, but `npm` can be also used to install packages that are designed to run both in Node and in a browser. In this case we use Node's `require` to load a module from the package in Node, but we can use `<script>` or Browserify or RequireJS to load the same module in a browser. What method to use in the browser really depends on how the package was designed. You have to read the doc to know or read the source code if the doc is not good. I've designed a `npm` package that works this way. You can use Node's `require` to load it in Node and use RequireJS to load it in a browser.

`npm` can even be used to install packages that are designed to run only in a browser. In this case, `npm` is just a convenient delivery and dependency mechanism. I have another package designed this way. It comes with a prominent note that it is not made to run in Node. This is an accepted usage of `npm` and there are currently proposals (here and here) to make `npm` even better at handling this kind of scenario.

Problem

Looking at `npm` starred packages I see that some projects like Grunt, lodash or underscore are avaliable. I've always used these in the classic way: ``` <script src="js/lib/lodash.min.js"></script> ``` What makes it different and how would I use them obtained within the `node_modules` packages?

Original source