You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeError: yaml.Schema.create is not a function错误排查与解决——基于TypeScript/Node.js环境的js-yaml 4.1.0问题

解决js-yaml 4.x中yaml.Schema.create is not a function的错误

这个报错的核心原因是js-yaml 4.x版本对Schema相关API做了重大重构,你参考的代码是基于旧版本(比如3.x)的写法,而4.x已经移除了Schema.create()方法。

下面是适配js-yaml 4.1.0版本的修正代码:

import * as yaml from 'js-yaml';

// 定义所有CloudFormation自定义YAML类型
const CF_TYPES = [
    new yaml.Type('!Ref', {
        kind: 'scalar',
        construct: (data) => ({ Ref: data }),
    }),
    new yaml.Type('!Equals', {
        kind: 'sequence',
        construct: (data) => ({ 'Fn::Equals': data }),
    }),
    new yaml.Type('!Not', {
        kind: 'sequence',
        construct: (data) => ({ 'Fn::Not': data }),
    }),
    new yaml.Type('!Sub', {
        kind: 'scalar',
        construct: (data) => ({ 'Fn::Sub': data }),
    }),
    new yaml.Type('!If', {
        kind: 'sequence',
        construct: (data) => ({ 'Fn::If': data }),
    }),
    new yaml.Type('!Join', {
        kind: 'sequence',
        construct: (data) => ({ 'Fn::Join': data }),
    }),
    new yaml.Type('!Select', {
        kind: 'sequence',
        construct: (data) => ({ 'Fn::Select': data }),
    }),
    new yaml.Type('!FindInMap', {
        kind: 'sequence',
        construct: (data) => ({ 'Fn::FindInMap': data }),
    }),
    new yaml.Type('!GetAtt', {
        kind: 'sequence',
        construct: (data) => ({ 'Fn::GetAtt': data }),
    }),
    new yaml.Type('!GetAZs', {
        kind: 'scalar',
        construct: (data) => ({ 'Fn::GetAZs': data }),
    }),
    new yaml.Type('!Base64', {
        kind: 'mapping',
        construct: (data) => ({ 'Fn::Base64': data }),
    }),
];

// 4.x版本创建自定义Schema的正确方式:扩展默认Schema
const CF_SCHEMA = yaml.DEFAULT_SCHEMA.extend(CF_TYPES);

关键变化说明:

  1. 替换Schema.create()为DEFAULT_SCHEMA.extend():
    旧版本的Schema.create()用来创建包含自定义类型的Schema,在4.x中你需要通过yaml.DEFAULT_SCHEMA.extend(types)来基于默认YAML Schema扩展自定义类型,这样既保留了基础YAML类型的支持,又能使用你定义的CloudFormation函数类型。

  2. (可选)直接创建全新Schema:
    如果你不需要默认的YAML类型支持,也可以直接通过Schema构造函数创建:

    const CF_SCHEMA = new yaml.Schema({ types: CF_TYPES });
    

为什么会出现这个错误?

你参考的代码是针对js-yaml 3.x版本编写的,而4.x版本对Schema系统进行了重写,移除了旧的Schema.create()静态方法,改用构造函数和扩展方法来实现自定义Schema的需求。

内容的提问来源于stack exchange,提问作者Sabo Boz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 22:22:50