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: