首頁 > web前端 > js教程 > 主體

使用 package.json 腳本增強'npm run dev”

PHPz
發布: 2024-07-24 12:02:51
原創
431 人瀏覽過

Supercharge `npm run dev` with package.json scripts

npm run dev 是「在本地運行我的網站」的標準,但它是如何運作的呢?我們如何擴充它的功能?在這篇文章中,我們將看看:

  • 如何設定 npm run dev 的功能。
  • 如何將複雜的命令分解為細粒度的單元。
  • 如何並行運行多個命令。
  • 如何在不失去正常 Ctrl-C 行為的情況下運行先決條件。
  • 啟動 Convex 後端時如何新增種子資料(如果不存在)。

作為一個激勵範例,以下是凸幫助程式範例應用程式中定義的一些腳本。我們將介紹每個部分的作用

雷雷

它們的定義方式和位置

npm run 執行專案工作區中 package.json 中定義的指令。當您從 npm create vite@latest 等命令啟動儲存庫時,這些命令通常是預先配置的,其中的命令為:

  • dev:運行開發環境。這通常包括在檔案更改時自動重新載入 UI。對 Vite 來說,這是 vite,Next.js 是下一個 dev。
  • build:建立用於部署的網站。這通常會編譯並捆綁所有 html、css 和 javascript。對於 Vite,這是 vite 構建,Next.js 是下一個構建。
  • test:執行測試 - 如果您使用 Jest,只需「test」:「jest」或 vitest for Vitest。

這是來自 Next.js 的基本範例:

雷雷

在這裡你可以運行 npm run dev 或 npm run lint 等

您可以在文件中了解有關 npm run 的更多資訊。

為什麼要使用腳本?

這是一個公平的問題,為什麼人們會將已經如此簡單的命令放入套件腳本中。為什麼不直接呼叫 jest 或 vite 或 next build 呢?有幾個很好的理由:

  1. 您可以儲存指令的預設參數,這樣您就不必記住或記錄啟動某項操作的「標準」方式。我們將在下面看到如何將其配置為連結命令並並行運行其他命令。
  2. 它允許您輕鬆運行由 npm 安裝但無法從 shell(終端)全局存取的命令。 1 當您安裝 npm install -D vitest 之類的東西時,它會將 vitest 安裝到 node_modules/.bin 中。 2你不能直接在 shell 中運行 vitest,3 但你可以有一個像這樣的配置: "scripts": { "test": "vitest" } 並且 npm run test 將運行 vitest。
  3. 即使您位於子目錄中,它也始終以套件資料夾的根目錄作為「目前目錄」運行。因此,您可以定義一個類似 "foo": "./myscript.sh" 的腳本,它總是會在套件根目錄中(與 package.json 位於同一目錄中)尋找 myscript.sh。注意:您可以透過 INIT_CWD 環境變數存取目前呼叫的目錄。
  4. 當腳本從 npm run 執行時,您可以輕鬆引用 package.json 中的變數。例如,您可以使用 npm_package_version 環境變數存取套件的“版本”,例如 js 中的 process.env.npm_package_version 或腳本中的 $npm_package_version 。
  5. 如果您有多個工作區(許多目錄都有自己的package.json,並透過「workspaces」設定配置到父package.json 中),則可以使用npm test --workspaces 或使用npm run 在所有工作區中運行相同的命令lint --workspace 應用程式/web.

npm run dev 可以與yarn/pnpm/bun一起使用嗎?

是的!即使您使用其他套件管理器安裝依賴項,您仍然可以使用 npm 運行套件腳本。

雷雷

您不必記住 npm run dev 對應到yarn dev(或yarn run dev)。 npx 也是如此:無論您使用什麼套件管理器來安裝東西,npx 凸開發都可以運作。

並行運行命令

有幾個套件可以用來同時執行指令:4

  1. npm-run-all
  2. 同時

我們在這裡只看一下 npm-run-all 。考慮我們的例子:

雷雷

這定義了三個腳本。

  1. npm run dev:後端運行凸開發。
  2. npm run dev:frontend 運行 vite。
  3. npm run dev 透過 npm-run-all 並行運行凸開發和 vite。

兩個輸出都會流出,執行 Ctrl-C 會中斷兩個腳本。

預開發?後期構建?

您可以透過將命令命名為 preX 或 postX 來指定在另一個命令(例如 X)之前(前)或之後(後)運行的命令。在範例中:

雷雷

這將在 npm-run-all --parallel dev:backend dev:frontend 的「dev」指令之前執行凸開發 --until-success。

Chaining with "&&"

For those used to shell scripting, you can run two commands in sequence if the previous one succeeds with commandA && commandB. This works on both Windows and Unix (mac / linux).

However, there's a couple advantages to just using pre-scripts:

  1. You can run either command with npm run dev --ignore-scripts to not do the "predev" script, or npm run predev to explicitly only do the "predev" step.
  2. The Ctrl-C behavior is more predictable in my experience. In different shell environments, doing Ctrl-C (which sends an interrupt signal to the current process) would sometimes kill the first script but still run the second script. After many attempts we decided to switch to "predev" as the pattern.

Run interactive steps first

For Convex, when you first run npx convex dev (or npm run dev with the above scripts), it will ask you to log in if you aren't already, and ask you to set up your project if one isn't already set up. This is great, but interactive commands that update the output text don't work well when the output is being streamed by multiple commands at once. This is the motivation for running npx convex dev --until-success before npx convex dev.

  • convex dev syncs your functions and schema whenever it doesn't match what you have deployed, watching for file changes.
  • The --until-success flag syncs your functions and schema only until it succeeds once, telling you what to fix if something is wrong and retrying automatically until it succeeds or you Ctrl-C it.
  • By running npx convex dev --until-success, we can go through the login, project configuration, and an initial sync, all before trying to start up the frontend and backend.
  • The initial sync is especially helpful if it catches issues like missing environment variables which need to be set before your app can function.
  • This way the frontend doesn't start until the backend is ready to handle requests with the version of functions it expects.

Seeding data on startup

If you change your "predev" command for Convex to include --run it will run a server-side function before your frontend has started.

  "scripts": {
      //...
    "predev": "convex dev --until-success --run init",
        //...
  },
登入後複製

The --run init command will run a function that is the default export in convex/init.ts. You could also have run --run myFolder/myModule:myFunction. See docs on naming here. See this post on seeding data but the gist is that you can define an internalMutation that checks if the database is empty, and if so inserts a collection of records for testing / setup purposes.

tsc?

If you use TypeScript, you can run a type check / compile your typescript files with a bare tsc. If your tsconfig.json is configured to emit types, it will write out the types. If not, it will just validate the types. This is great to do as part of the build, so you don't build anything that has type errors. This is why the above example did:

    "build": "tsc && vite build",
登入後複製

How to pass arguments?

If you want to pass arguments to a command, for instance passing arguments to your testing command to specify what test to run, you can pass them after a -- to separate the command from the argument. Technically you don't need -- if your arguments are positional instead of --prefixed, but it doesn't hurt to always do it in case you forget which to do it for.

npm run test -- --grep="pattern"
登入後複製

Summary

We looked at some ways of using package.json scripts to simplify our workflows. Who knew how much power could rest behind a simple npm run dev? Looking at our original example:

  "scripts": {
    "dev": "npm-run-all --parallel dev:backend dev:frontend",
    "build": "tsc && vite build",
    "dev:backend": "convex dev",
    "dev:frontend": "vite",
    "predev": "convex dev --until-success",
    "test": "vitest"
  },
登入後複製
  • dev runs the frontend and backend in parallel, after predev.
  • build does type checking via tsc before building the static site.
  • dev:backend continuously deploys the backend functions to your development environment as you edit files.
  • dev:frontend runs a local frontend server that auto-reloads as you edit files.
  • predev runs before dev and does an initial deployment, handling login, configuration, and an initial sync as necessary.
  • test uses Vitest to run tests. Note: npm test is shorthand for npm run test along with other commands, but they're special cases. npm run test is the habit I suggest.

  1. The way your shell finds which command to run when you type npm is to check the shell's PATH environment variable (on unix machines anyways). You can see your own with echo "$PATH". It checks all the places specified in $PATH and uses the first one.  ↩

  2. Technically you can override & specify where npm installs binaries. ↩

  3. 如果你真的想,你可以直接執行 npm exec vitest,簡稱 npx vitest,./npm_modules/.bin/vitest,或是將 .npm_modules/.bin 加到你的 PATH 中。 ↩

  4. 有些人使用裸 & 在後台運行一項任務,但這在 Windows 上不受支持,並且中斷一個命令不一定會殺死另一個命令。 ↩

以上是使用 package.json 腳本增強'npm run dev”的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!