The difference between NPM and NPX
Recently, I have been learning to rebuild this website in Astro, using an external headless CMS for the content management.
I have currently settled on WordPress, but along the way I trialed Sanity
In their official documentation for the Sanity Astro plugin, they instruct you to install it using the command npx astro add @sanity/astro @astrojs/react
which got me thinking – what is NPX and how does it differ from NPM?
What is NPM?
NPM stands for Node Package Manager, which is used to manage dependencies in Node.js and other JavaScript (including TypeScript) based projects.
To install a dependency into a project, you type npm install package-name
(or npm i package-name
for shorthand) into the console in the root of your project. This then installs the dependency into a folder called node_modules
in the root of your project.
(Important aside – it is best practice not to commit the node_modules
folder to your version control system)
References to these dependencies, and their version, are then added to a file in the root of your project called package.json
– ensuring these dependencies can be tracked and reinstalled across all environments your project is installed.
What is NPX?
NPX stands for Node Package eXecute, as the name implies, executes Node.js packages without installing them into your project.
This is handy when the use case of the dependency is to run as a one-off, and not adding the dependency to your project permanently.
NPX can also be used to execute code directly from GitHub (Gist or Repo) or another publicly visible Repository – should it conform to NPM package standards
npx https://gist.github.com/[UserName]/[UUID]
Lastly, it can be used to test different package versions
npx create-react-app@[version] [subdirectory]
cd [subdirectory]
npm start
This will quickly spin up a clean copy of create_react_app
in a subfolder, and allow you to test that specific version – particularly useful to test the “next” or “alpha/beta” version of a given project.
In Conclusion – NPM v NPX
NPM is used to install, delete and update JavaScript dependencies within your project.
NPX is used to execute JavaScript dependencies in a one of case, without installing them.