This article is a mirror article of machine translation, please click here to jump to the original article.

View: 8780|Reply: 0

npm tutorial (4): Install npm packages locally

[Copy link]
Posted on 12/13/2017 1:23:35 PM | | | |
There are two ways to install npm packages: local or global. You can choose which installation to use based on the package you want to use.

If you want to rely on your own modules to use a Node.js-like require, then you want to install locally, which is the default behavior of npm install. On the other hand, if you want to use it as a command line tool, like the grunt CLI, then you want to install it globally.


Installation

A package can be downloaded with the following command:

This will create node_modules directory in the current directory if it doesn't already exist and download the package to that directory.

Test:

To confirm that npm install is working, check if the node_modules directory exists and that it contains the directory of the package you installed. You can run ls node_modules on a Unix system to do this job. "OSX", "Debian" or dir node_modules on Windows.

Example:



Install a package called lodash. Confirm that it is running successfully by listing the contents of node_modules directory and looking at the directory named lodash.


If you don't have package.json file in your local directory, install the latest version of the package.

If there is a package.json or package-lock.json file, then the latest version, if any, that satisfies the semver rules declared in the package.json will be installed.

Use the installed package

Once the package is in the node_modules, you can use it in your code. For example, if you're creating a Node.js module, you can request it.

Example:

Create a file called index.js with the following code:


The correct output result is: [2, 3]



If you don't install lodash correctly, you get this error:

If you had not properly installed lodash, you would receive this error:

module.js:340
    throw err;
          ^
Error: Cannot find module 'lodash'

To fix this, run npm install lodash in the directory where your index.js is located.






Previous:What is the package-lock.json generated by npm install?
Next:npm tutorial (5): How to use package.json tutorial
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com