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

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

Jul 24, 2024 pm 12:02 PM

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

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1667
14
CakePHP 教程
1426
52
Laravel 教程
1328
25
PHP教程
1273
29
C# 教程
1255
24
JavaScript引擎:比较实施 JavaScript引擎:比较实施 Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和执行JavaScript代码时,效果会有所不同,因为每个引擎的实现原理和优化策略各有差异。1.词法分析:将源码转换为词法单元。2.语法分析:生成抽象语法树。3.优化和编译:通过JIT编译器生成机器码。4.执行:运行机器码。V8引擎通过即时编译和隐藏类优化,SpiderMonkey使用类型推断系统,导致在相同代码上的性能表现不同。

Python vs. JavaScript:学习曲线和易用性 Python vs. JavaScript:学习曲线和易用性 Apr 16, 2025 am 12:12 AM

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

从C/C到JavaScript:所有工作方式 从C/C到JavaScript:所有工作方式 Apr 14, 2025 am 12:05 AM

从C/C 转向JavaScript需要适应动态类型、垃圾回收和异步编程等特点。1)C/C 是静态类型语言,需手动管理内存,而JavaScript是动态类型,垃圾回收自动处理。2)C/C 需编译成机器码,JavaScript则为解释型语言。3)JavaScript引入闭包、原型链和Promise等概念,增强了灵活性和异步编程能力。

JavaScript和Web:核心功能和用例 JavaScript和Web:核心功能和用例 Apr 18, 2025 am 12:19 AM

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

JavaScript在行动中:现实世界中的示例和项目 JavaScript在行动中:现实世界中的示例和项目 Apr 19, 2025 am 12:13 AM

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

了解JavaScript引擎:实施详细信息 了解JavaScript引擎:实施详细信息 Apr 17, 2025 am 12:05 AM

理解JavaScript引擎内部工作原理对开发者重要,因为它能帮助编写更高效的代码并理解性能瓶颈和优化策略。1)引擎的工作流程包括解析、编译和执行三个阶段;2)执行过程中,引擎会进行动态优化,如内联缓存和隐藏类;3)最佳实践包括避免全局变量、优化循环、使用const和let,以及避免过度使用闭包。

Python vs. JavaScript:社区,图书馆和资源 Python vs. JavaScript:社区,图书馆和资源 Apr 15, 2025 am 12:16 AM

Python和JavaScript在社区、库和资源方面的对比各有优劣。1)Python社区友好,适合初学者,但前端开发资源不如JavaScript丰富。2)Python在数据科学和机器学习库方面强大,JavaScript则在前端开发库和框架上更胜一筹。3)两者的学习资源都丰富,但Python适合从官方文档开始,JavaScript则以MDNWebDocs为佳。选择应基于项目需求和个人兴趣。

Python vs. JavaScript:开发环境和工具 Python vs. JavaScript:开发环境和工具 Apr 26, 2025 am 12:09 AM

Python和JavaScript在开发环境上的选择都很重要。1)Python的开发环境包括PyCharm、JupyterNotebook和Anaconda,适合数据科学和快速原型开发。2)JavaScript的开发环境包括Node.js、VSCode和Webpack,适用于前端和后端开发。根据项目需求选择合适的工具可以提高开发效率和项目成功率。

See all articles