init

将工作脚本复制到给定目录中。

用法

¥Usage

npx msw init <PUBLIC_DIR> [options]

参数

¥Arguments

PUBLIC_DIR

应用公共目录的相对路径。

¥A relative path to the public directory of your application.

例如,使用 NextJS 时,公共目录位于 /public,这是你应该提供给此命令的路径:

¥For example, when using NextJS, the public directory is located in /public, and that’s the path you should provide to this command:

npx msw init ./public

标志

¥Flags

--save

将给定的 PUBLIC_DIR 保存在 package.json 中,以便将来自动更新工作脚本。

¥Save the given PUBLIC_DIR in package.json for future automatic updates of the worker script.

npx msw init ./public --save

运行此命令将在你的 package.json 中保存 ./public 目录:

¥Running this command will save the ./public directory in your package.json:

// package.json
{
  "name": "my-app",
  "msw": {
    "workerDirectory": "./public"
  }
}

如果存在此属性,则每当你安装 msw 包时,工作脚本都会自动复制到 msw.workerDirectory 目标。这可确保工作脚本与当前安装的库版本同步。

¥If this property is present, whenever you install the msw package, the worker script will be copied to the msw.workerDirectory destination automatically. This ensures the worker script being in sync with the currently installed version of the library.

--save 标志相对应,你可以提供 --no-save 标志,该标志不会提示你保存工作脚本位置。当在自动化环境中运行 MSW 时,如果不希望终端交互,这会非常方便。请注意,即使提供了 --no-save 标志,如果你之前在 package.json 中的 msw.workerDirectory 下保存了工作脚本位置,MSW 仍会将这些位置作为 init 命令的一部分进行更新。

¥As a counterpart to the --save flag, you can provide the --no-save flag that will not prompt you to save the worker script location. This can be handy when running MSW in automated environments where terminal interactivity is not desirabble. Note that even with the --no-save flag provided, if you have worker script locations previously saved under msw.workerDirectory in package.json, MSW will still update those locations as a part of the init command.

相关材料

¥Related materials

Managing the worker

Learn how to manage the worker script updates.