npm 和 npx
npm
Node Package Manger,是 nodejs 的 dependency/package manager,提供開發者 install packages both globally and locally。
- 提供 online repository 可以 publish
open-source Node.js projects - 提供
CLI tool讓開發者 install packages and manage their versions and dependencies
如果想使用npm 去 run a package,必須在 package.json 檔案裡指定 package。 當 executables are installed via npm packages, npm creates links to them:
- local installs have links created at the
./node_modules/.bin/ directory - global installs have links created from the global
bin/directory (for example:/usr/local/binon Linux or at%AppData%/npmon Windows)
To execute a package with npm 有兩種方法:
- 指定路徑
$ ./node_modules/.bin/your-package - adding it into your package.json file in the scripts section
{ "name": "your-application", "version": "1.0.0", "scripts": { "your-package": "your-package" } }
接下來就可以 run the script using npm run:
$ npm run your-package
以上就是使用 npm run a package 麻煩的地方。
所以接下來介紹npx。
npx
npm 只要更新到 npm@5.2.0 後,就會多出一個 npx 指令。
npx使用情況:
Run a locally installed package easily
如果想要執行 locally installed package,只需要 type:
$ npx your-package npx 會檢查 local 或 $PATH 裡是否存在 <command> or <package> 的 binaries,有的話便會執行。
Execute packages that are not previously installed
使用 npx 命令,他會安裝在臨時安裝包上,等到項目初始化完成後就刪除,不用全局性的安裝,避免被汙染。
Test different package versions
npx makes it extremely easy to test different versions of a Node.js package or module。
以下是示範 install the create-react-app package and test out an upcoming version。
$ npm v create-react-app
Let’s use npx to try out the next dist tag of create-react-app which will create the app inside a sandbox directory.
$ npx create-react-app@next sandbox npx 會暫時 install the next version 的 create-react-app,然後執行以搭建該應用並安裝其 dependencies。
安裝好後,我們可以進入資料夾並且執行 start command,它將在您的默認瀏覽器窗口中自動打開 React 應用。
$ cd sandbox
$ npm start
Run code directly from GitHub
在 terminal 輸入
$ npx https://gist.github.com/yu-shin/6e4b9d49ec00cc9b219ab6bfe72309ab
可以看到輸出 yay gist
Bonus Round: shell auto-fallback
待更新...