npx节点包运行器

npx是一种非常酷的运行Node代码的方式,并提供了许多有用的功能

在本文中,我想介绍一个非常强大的命令,该命令已在npm2017年7月发布的5.2版开始:像素

如果您不想安装npm,则可以将npx安装为独立软件包

npx使您可以运行使用Node构建并通过npm注册表发布的代码。

轻松运行本地命令

节点开发人员过去通常将大多数可执行命令发布为全局包,以使它们可以立即出现在路径中并可以执行。

这很痛苦,因为您无法真正安装同一命令的不同版本。

跑步npx commandname自动在内部找到正确的命令参考node_modules文件夹,而不需要知道确切的路径,也不需要将软件包安装在全局路径和用户路径中。

无需安装的命令执行

还有一个很大的特点npm,这允许在不先安装命令的情况下运行命令。

这非常有用,主要是因为:

1)您不需要安装任何内容2)您可以使用@version语法运行同一命令的不同版本

使用的典型演示npx通过cowsay命令。cowsay将显示一头母牛,说出您在命令中写的内容。例如:

cowsay "Hello"将打印

 _______
< Hello >
 -------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

Now, this if you have the cowsay command globally installed from npm previously, otherwise you’ll get an error when you try to run the command.

npx allows you to run that npm command without having it installed locally:

npx cowsay "Hello"

will do the job.

Now, this is a funny useless command. Other scenarios include:

  • running the vue CLI tool to create new applications and run them: npx vue create my-vue-app
  • creating a new React app using create-react-app: npx create-react-app my-react-app

and many more.

Once downloaded, the downloaded code will be wiped.

Run some code using a different Node version

Use the @ to specify the version, and combine that with the node npm package:

npx [email protected] -v #v6.14.3
npx [email protected] -v #v8.11.3

This helps to avoid tools like nvm or the other Node version management tools.

Run arbitrary code snippets directly from a URL

npx does not limit you to the packages published on the npm registry.

You can run code that sits in a GitHub gist, for example:

npx https://gist.github.com/zkat/4bc19503fe9e9309e2bfaa2c58074d32

Of course, you need to be careful when running code that you do not control, as with great power comes great responsibility.

Download my free Node.js Handbook


More node tutorials: