npm vs. npx - When should you use which?
Hello #FrontendFriday-reader,
Today we are looking at a topic that comes up again and again in the everyday life of a JavaScript developer: npm and npx. Both tools are essential, but when should you use which one? What are the exact differences? And what happens technically behind the scenes? Let's dive in!
npm - The package manager
npm stands for Node Package Manager and is the standard when it comes to managing packages and dependencies in the Node.js world.
With npm you can:
- Install packages - both locally for your project and globally for your entire system.
- Manage dependencies - The
package.json-file records which packages your project requires and in which version. - Execute scripts - About the
scripts-section in thepackage.jsonyou can define recurring tasks andnpm runexecute.
Example: To use the package express to your project, you use:
npm install express
This will express in the node_modules-folder of your project and installed as a dependency in the package.json noted.
npx - The Parcel Exporter
npx was introduced with npm version 5.2.0 and stands for Node Package Execute. It allows you to run Node.js packages directly without having to install them first.
When is npx useful?
- Unique designs - If you only need a package once or rarely, you can run it with npx without installing it globally.
- Test specific versions - You can run certain versions of a package, for example to carry out compatibility tests.
- Project setup - Tools like
create-react-appcan be started directly via npx without having to install them globally.
Example: To create a new React application, you can use the following command:
npx create-react-app mein-projekt
Here npx loads the latest create-react-app-package and executes it without installing it permanently.
Technical differences
The main difference between npm and npx lies in their functionality:
- npm - Installs packages and manages dependencies.
- npx - Executes packages without necessarily installing them.
Technically, npx searches for the package to be executed in the following order:
- Local in the project - In the
node_modules/.bin-directory of your project. - Global on your system - In the global npm modules.
- In the npm registry - If the package is not found locally or globally, npx temporarily downloads it from the npm registry and executes it.
This makes it possible to use packages flexibly and without prior installation, which is particularly helpful for one-off tasks or tests.
Conclusion
Both npm and npx are powerful tools in Node.js development. While npm is responsible for installing and managing packages, npx shines when it comes to executing packages quickly and easily without installing them permanently. Depending on your use case, you should decide which tool is more suitable.
I hope this overview helps you to better understand the differences and possible uses of npm and npx. Happy coding!1



