天天看点

Difference between npx and npm?

Difference between npx and npm?

<code>NPX</code> comes bundled with <code>NPM</code> version <code>5.2+</code>

<code>NPM</code> by itself does not simply run any package. it doesn't run any package in a matter of fact. If you want to run a package using NPM, you must specify that package in your <code>package.json</code> file.

When executables are installed via NPM packages, NPM links to them:

local installs have "links" created at <code>./node_modules/.bin/</code> directory.

global installs have "links" created from the global <code>bin/</code> directory (e.g. <code>/usr/local/bin</code>) on Linux or at <code>%AppData%/npm</code> on Windows.

Documentation you should read

NPM:

One might install a package locally on a certain project:

Now let's say you want NodeJS to execute that package from the command line:

The above will fail. Only globally installed packages can be executed by typing their name only.

To fix this, and have it run, you must type the local path:

You can technically run a locally installed package by editing your <code>packages.json</code> file and adding that package in the <code>scripts</code> section:

Then run the script using <code>npm run-script</code> (or <code>npm run</code>):

NPX:

<code>npx</code> will check whether <code>&lt;command&gt;</code> exists in <code>$PATH</code>, or in the local project binaries, and execute it. So, for the above example, if you wish to execute the locally-installed package <code>some-package</code> all you need to do is type:

Another major advantage of <code>npx</code> is the ability to execute a package which wasn't previously installed:

The above example will generate a <code>react</code> app boilerplate within the path the command had run in, and ensures that you always use the latest version of a generator or build tool without having to upgrade each time you’re about to use it.

<code>npx</code> command may be helpful in the <code>script</code> section of a <code>package.json</code> file, when it is unwanted to define a dependency which might not be commonly used or any other reason:

Call with: <code>npm run serve</code>

How to use package installed locally in node_modules?

NPM: how to source ./node_modules/.bin folder?

How do you run a js file using npm scripts?

继续阅读