# schema-utils 中文文档

规范地址：https://npmcn.com/package/schema-utils/

版本：4\.8\.2
npm 元数据更新时间：2026-10-31T16:52:45.209Z
中文译文更新时间：2026-11-05T14:47:37.334Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/schema-utils
原文对照：https://npmcn.com/package/schema-utils/?lang=original
项目主页：https://github.com/webpack/schema-utils
源码仓库：https://github.com/webpack/schema-utils

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：123 kB，30 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- Node.js 要求：\>= 10\.13\.0
- 运行依赖：4 个
- peer 依赖：webpack ^5\.112\.0
- 首次发布：2017-03-07T06:01:28.207Z
- 最新版本发布：2026-10-31T16:52:44.881Z
- 近 30 天下载量：460723607（2026-10-05 至 2026-11-03，npm 官方下载统计）
- 已发布版本数：50（近 12 个月 7 个）

## 中文简介

网络包验证工具

## 安装

```sh
npm install schema-utils
```

也可以使用：`pnpm add schema-utils`、`yarn add schema-utils`、`bun add schema-utils`

## README

 [![](https://raw.githubusercontent.com/webpack-contrib/schema-utils/main/.github/assets/logo.png)](http://json-schema.org/)[![](https://webpack.js.org/assets/icon-square-big.svg)](https://github.com/webpack/webpack)

[![npm](https://img.shields.io/npm/v/schema-utils.svg)](https://npmjs.com/package/schema-utils) [![node](https://img.shields.io/node/v/schema-utils.svg)](https://nodejs.org/) [![tests](https://github.com/webpack/schema-utils/workflows/schema-utils/badge.svg)](https://github.com/webpack/schema-utils/actions) [![coverage](https://codecov.io/gh/webpack/schema-utils/branch/main/graph/badge.svg)](https://codecov.io/gh/webpack/schema-utils) [![GitHub Discussions](https://img.shields.io/github/discussions/webpack/webpack)](https://github.com/webpack/webpack/discussions) [![size](https://packagephobia.com/badge?p=schema-utils)](https://packagephobia.com/result?p=schema-utils)

# 计划图

用于加载器和插件中验证选项的软件包 .

## 开始

开始,你需要安装 `schema-utils`数字 :

```console
npm install schema-utils
```

## API 密码

**计划.json**

```json
{
  "type": "object",
  "properties": {
    "option": {
      "type": "boolean"
    }
  },
  "additionalProperties": false
}
```

```js
import { validate } from "schema-utils";
import schema from "./path/to/schema.json";

const options = { option: true };
const configuration = { name: "Loader Name/Plugin Name/Name" };

validate(schema, options, configuration);
```

### `schema`

类型 : `String`

JSON计划.

简单的计划示例 :

```json
{
  "type": "object",
  "properties": {
    "name": {
      "description": "This is description of option.",
      "type": "string"
    }
  },
  "additionalProperties": false
}
```

### `options`

类型 : `Object`

带有选项的对象 .

```js
import { validate } from "schema-utils";
import schema from "./path/to/schema.json";

const options = { foo: "bar" };

validate(schema, { name: 123 }, { name: "MyPlugin" });
```

### `configuration`

允许配置验证符 .

配置 `name` 财务报告和审定财务报表`baseDataPath` 通过 `title` 财产在计划. 例如:

```json
{
  "title": "My Loader options",
  "type": "object",
  "properties": {
    "name": {
      "description": "This is description of option.",
      "type": "string"
    }
  },
  "additionalProperties": false
}
```

用于 `baseDataPath` 选项,用于 `name` 选项. 根据上文的例子 `name` 选项等于 `My Loader`,则 `baseDataPath` 选项等于 `options`。 。 。 .

#### `name`

类型 : `Object` 默认 : `"Object"`

允许在验证错误中设置名称 .

```js
import { validate } from "schema-utils";
import schema from "./path/to/schema.json";

const options = { foo: "bar" };

validate(schema, options, { name: "MyPlugin" });
```

```shell
Invalid configuration object. MyPlugin has been initialised using a configuration object that does not match the API schema.
 - configuration.optionName should be a integer.
```

#### `baseDataPath`

类型 : `String` 默认 : `"configuration"`

允许在验证错误中设置基础数据路径.

```js
import { validate } from "schema-utils";
import schema from "./path/to/schema.json";

const options = { foo: "bar" };

validate(schema, options, { name: "MyPlugin", baseDataPath: "options" });
```

```shell
Invalid options object. MyPlugin has been initialised using an options object that does not match the API schema.
 - options.optionName should be a integer.
```

#### `postFormatter`

类型 : `Function` 默认 : `undefined`

允许重塑错误 .

```js
import { validate } from "schema-utils";
import schema from "./path/to/schema.json";

const options = { foo: "bar" };

validate(schema, options, {
  name: "MyPlugin",
  postFormatter: (formattedError, error) => {
    if (error.keyword === "type") {
      return `${formattedError}\nAdditional Information.`;
    }

    return formattedError;
  },
});
```

```shell
Invalid options object. MyPlugin has been initialized using an options object that does not match the API schema.
 - options.optionName should be a integer.
   Additional Information.
```

## 实例

**计划.json**

```json
{
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "test": {
      "anyOf": [
        { "type": "array" },
        { "type": "string" },
        { "instanceof": "RegExp" }
      ]
    },
    "transform": {
      "instanceof": "Function"
    },
    "sourceMap": {
      "type": "boolean"
    }
  },
  "additionalProperties": false
}
```

### `Loader`

```js
import schema from "path/to/schema.json";
import { getOptions } from "loader-utils";
import { validate } from "schema-utils";

function loader(src, map) {
  const options = getOptions(this);

  validate(schema, options, {
    name: "Loader Name",
    baseDataPath: "options",
  });

  // Code...
}

export default loader;
```

### `Plugin`

```js
import schema from "path/to/schema.json";
import { validate } from "schema-utils";

class Plugin {
  constructor(options) {
    validate(schema, options, {
      name: "Plugin Name",
      baseDataPath: "options",
    });

    this.options = options;
  }

  apply(compiler) {
    // Code...
  }
}

export default Plugin;
```

### 预编方案

在运行时负载时编译一个计划 `ajv`,这需要大约150ms 用于第一个计划a 工艺和每用一毫秒至一毫秒。 装入器或插件可以编译它 提前计划,而不是在检查中 `validate` 第四项论点是:

```console
npx schema-utils precompile src/options.json
```

这个写着 `src/options.check.js` 在计划旁边。 上交,并用软件包发布:

```js
import { validate } from "schema-utils";
import check from "./options.check.js";
import schema from "./options.json";

validate(schema, options, { name: "Loader Name" }, check);
```

当选项有效时,检查就是运行和 `ajv` 从未装入。 当他们 没有, `validate` 运行全部验证以报告错误,所以错误与 没有支票.

运行 `schema-utils precompile --check src/options.json` 在 CI 中, 当检查缺失时失败或 已经过时了 生成的模块可能需要 `schema-utils` 的附属关系 软件包。 它是一个ES模块 当最近的 `package.json` 已经 `"type": "module"`节点的方式 读取 `.js` 存档, 普通JS 除外.

与 `--minify`中,检查会删除它从未报告的错误对象,并有帮助者写入 而不是从 `schema-utils`,并用 webpack 本身的修饰器进行修改,需要 网络包装5.112.0或以后。 对于Webpack自己的选项,其尺寸和负载都不到一半 13米取而代之为21米. `--check` 必须给予同样的 `--minify` 比较正确的代码.

一个亲戚 `$ref` 到另一个文件 解决与计划。 从代码中编译一个计划, 使用 `precompile(schema, { loadSchema, esm, minify })`,它返回模块的来源.

### 允许禁用和启用验证(即 `validate` 函数什么都不做)

当您不想进行验证时, 这会有所帮助 `production` 建设.

```js
import { disableValidation, enableValidation, validate } from "schema-utils";

// Disable validation
disableValidation();
// Do nothing
validate(schema, options);

// Enable validation
enableValidation();
// Will throw an error if schema is not valid
validate(schema, options);

// Allow to undestand do you need validation or not
const need = needValidate();

console.log(need);
```

您也可以使用 `process.env.SKIP_VALIDATION` env变量.

支持的值( 大小写不敏感) :

-   `yes`编号 :`y`编号 :`true`编号 :`1`编号 :`on`
-   `no`编号 :`n`编号 :`false`编号 :`0`编号 :`off`

变量在 `schema-utils` 已装入,故在进程开始前设置:

```console
SKIP_VALIDATION=y webpack
```

使用 `enableValidation()`编号 :`disableValidation()` 在进程运行时更改它 - 它们 立即生效,并适用于每份 `schema-utils` 过程.

## 捐款

请花点时间来读一下我们的贡献准则 如果你还没有这样做.

[捐款](https://github.com/webpack/schema-utils?tab=contributing-ov-file#contributing)

软件包本身运行于Node.js 10.13.0及以上,但非依赖性需要活性 LTS发布,所以使用一个来工作. CI 安装更年长的,对老年人进行测试 软件包支持的Node.js版本.

## 许可证

[麻省理工学院](https://npmcn.com/package/schema-utils/LICENSE)

## 常见问题

### schema-utils 是什么？

网络包验证工具

### 如何安装 schema-utils？

在项目目录运行 npm install schema-utils，或使用 pnpm add / yarn add / bun add。它还提供命令行工具 schema-utils，可以用 npx schema-utils 直接运行。

### schema-utils 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### schema-utils 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### schema-utils 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>= 10\.13\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### schema-utils 可以商用吗？

schema-utils 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### schema-utils 的下载量有多少？

根据 npm 官方下载统计，schema-utils 在 2026/10/05 – 2026/11/03 这 30 天内被下载 460,723,607 次，日均约 15,357,454 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### schema-utils 还在维护吗？

最新版本 4\.8\.2 发布于 2026/11/01（5 天前）；至今共发布 50 个版本，其中过去 12 个月发布了 7 个；首次发布于 2017/03/07。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

