首页 >web前端 >js教程 >使用 package.json 脚本增强'npm run dev”

使用 package.json 脚本增强'npm run dev”

PHPz
PHPz原创
2024-07-24 12:02:51618浏览

Supercharge `npm run dev` with package.json scripts

npm run dev 是“在本地运行我的网站”的标准,但它是如何工作的呢?我们如何扩展它的功能?在这篇文章中,我们将看看:

  • 如何配置 npm run dev 的功能。
  • 如何将复杂的命令分解为细粒度的单元。
  • 如何并行运行多个命令。
  • 如何在不失去正常 Ctrl-C 行为的情况下运行先决条件。
  • 启动 Convex 后端时如何添加种子数据(如果不存在)。

作为一个激励示例,以下是凸帮助程序示例应用程序中定义的一些脚本。我们将介绍每个部分的作用

  "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"
  },
它们的定义方式和位置

npm run 运行项目工作区中 package.json 中定义的命令。当您从 npm create vite@latest 等命令启动存储库时,这些命令通常是预先配置的,其中的命令为:

    dev:运行开发环境。这通常包括在文件更改时自动重新加载 UI。对于 Vite 来说,这是 vite,Next.js 是 next dev。
  • build:构建用于部署的网站。这通常会编译并捆绑所有 html、css 和 javascript。对于 Vite,这是 vite 构建,Next.js 是下一个构建。
  • test:运行测试 - 如果您使用 Jest,则只需“test”:“jest”或 vitest for Vitest。
这是来自 Next.js 的基本示例:


// in package.json
{
// ...
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
//...
在这里你可以运行 npm run dev 或 npm run lint 等

您可以在文档中了解有关 npm run 的更多信息。

为什么使用脚本?

这是一个公平的问题,为什么人们会将已经如此简单的命令放入包脚本中。为什么不直接调用 jest 或 vite 或 next build 呢?有几个很好的理由:

    您可以保存命令的默认参数,这样您就不必记住或记录启动某项操作的“标准”方式。我们将在下面看到如何将其配置为链接命令并并行运行其他命令。
  1. 它允许您轻松运行由 npm 安装但无法从 shell(终端)全局访问的命令。
  2. 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 apps/web.
npm run dev 可以与yarn/pnpm/bun一起使用吗?

是的!即使您使用其他包管理器安装依赖项,您仍然可以使用 npm 运行包脚本。


yarn # similar to `npm install`
npm run dev # still works!
您不必记住 npm run dev 映射到yarn dev(或yarn run dev)。 npx 也是如此:无论您使用什么包管理器来安装东西,npx 凸开发都可以工作。

并行运行命令

有几个包可以用来同时运行命令:

4

    npm-run-all
  1. 同时
我们在这里只看一下 npm-run-all 。考虑我们的例子:


  "scripts": {
    "dev": "npm-run-all --parallel dev:backend dev:frontend",
    "dev:backend": "convex dev",
    "dev:frontend": "vite",
  },
这定义了三个脚本。

    npm run dev:后端运行凸开发。
  1. npm run dev:frontend 运行 vite。
  2. npm run dev 通过 npm-run-all 并行运行凸开发和 vite。
两个输出都会流出,并且执行 Ctrl-C 将中断两个脚本。

预开发?后期构建?

您可以通过将命令命名为 preX 或 postX 来指定在另一个命令(例如 X)之前(前)或之后(后)运行的命令。在示例中:


  "scripts": {
    "dev": "npm-run-all --parallel dev:backend dev:frontend",
    "dev:backend": "convex dev",
    "dev:frontend": "vite",
    "predev": "convex dev --until-success",
  },
这将在 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn