Npm
is the default package manager for the JavaScript runtime environment Node.js. It is used to install and manage packages (libraries, frameworks, utilities, etc.) that are published on the npm registry, as well as to manage dependencies and to run scripts defined in a project's package.json
file.
Here are some examples of how npm
can be used:
- To install a package and add it to your project’s
dependencies
:
$ npm install react --save
This will install the react
package and add it to the dependencies
section in your package.json
file. The --save
flag indicates that the package should be added to the dependencies
section, so that it will be installed when running npm install
in the future.
- To install a package and add it to your project’s
devDependencies
:
$ npm install jest --save-dev
This will install the jest
package and add it to the devDependencies
section in your package.json
file. The --save-dev
flag indicates that the package should be added to the devDependencies
section, which is used for development-only packages such as testing frameworks.
- To install a package globally:
$ npm install -g create-react-app
This will install the create-react-app
package globally on your system, allowing you to use it from any directory. The -g
flag indicates that the package should be installed globally.
- To run a script defined in a package’s
package.json
file:
$ npm run test
This will run the test
script defined in your package.json
file. This might be used to run tests for your project, for example.
NPX
is a tool that is also included with npm. It allows you to run Node.js packages that are installed locally or globally in your project, without the need to install them globally on your system. This can be useful if you want to use a package temporarily for a one-off command, or if you want to ensure that you are using the correct version of a package that is specified in your project's package.json
file.
Here are some examples of how npx
can be used:
- To run a package’s command-line interface:
$ npx create-react-app my-app
This will create a new React app in the my-app
directory, using the create-react-app
package. You don't need to have create-react-app
installed globally on your system in order to use it.
- To run a script defined in a package’s
package.json
file:
$ npx react-scripts test
This will run the test
script defined in the react-scripts
package, which is typically used to run tests for a React app.
- To run a package that is not installed in your project:
$ npx cowsay "Hello, world!"
This will run the cowsay
package, which displays a message in a cow-like ASCII art. The package will be downloaded and run temporarily, without the need to install it globally or locally in your project.