webpack5 schema-utils

Published: · LastMod: April 07, 2024 · 500 words

schema-utils 🔗

webpack中工具类schema-utils 🔗

yarn add -D schema-utils

webpack中调用 schema-utils 校验配置对象

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// options.json
{
  "type": "object",
  "properties": {
    "name": {
      "type": "boolean"
    }
  },
  "required": ["name"],
  "additionalProperties": false
}

schema-utils底层依赖ajv js

ajv 🔗

ajv支持7种默认基本数据类型

  • number

  • interger

  • string

  • boolean

  • array

  • null

  • object

    • maxProperties / minProperties:限定对象支持的最多、最少属性数量;

    • required:声明哪些属性不可为空,例如 required = ['name', 'age'] 时,传入的值必须至少提供 name/age 属性;

    • properties:定义特定属性的 Schema 描述,与 arrayitems 属性类似,支持嵌套规则,例如:

  • patternProperties: 支持属性名正则表达式

  • additionalProperties

  • enum: 枚举数组, 必须相等

  • const 静态变量

  • not指令: 数值必须不能等于这个值

  • anyof指令: 必须满足条件之一

  • oneof指令: 数值必须满足且只能满足条件之一

  • allof指令: 必须满足所有条件

  • if/then/else: 条件复合条件

异步校验 🔗

shema必须加上$async属性

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
jv.addKeyword({
  keyword: "idExists",
  async: true,
  type: "number",
  validate: checkIdExists,
})

async function checkIdExists(schema, data) {
  // .....
}

const schema = {
  $async: true,
  properties: {
    userId: {
      type: "integer",
      idExists: {table: "users"},
    },
    postId: {
      type: "integer",
      idExists: {table: "posts"},
    },
  },
}

const validate = ajv.compile(schema)

validate({userId: 1, postId: 19})
  .then(function (data) {
    // ....
  })

最终在校验对象时,validate会返回一个Promise对象