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

esbuild构建时读取YAML文件报错globRequire_yaml未定义

问题

我的应用用YAML文件存储i18next翻译内容,在create-react-app(搭配CRACO)开发环境下读取YAML文件完全正常,但用esbuild构建部署包后,应用崩溃,控制台报错:

index.ts:4 Uncaught ReferenceError: globRequire_yaml is not defined
    at index.ts:4:28
    at Array.forEach (<anonymous>)
    at index.ts:3:44
    at index.ts:4:72

报错代码片段:

["de", "en", "es", "fr", "ja", "pt", "zh"].forEach((locale) => {
  const contents = require(`./${locale}.yml`);  // <---- 报错位置
  Object.assign(locales, contents);
});

我的esbuild配置文件(.esBuild.js)如下:

const esbuild = require("esbuild");
const { sassPlugin } = require("esbuild-sass-plugin");
const inlineImportPlugin = require("esbuild-plugin-inline-import");
const { yamlPlugin } = require("esbuild-plugin-yaml");

esbuild
  .build({
    entryPoints: ["src/index.js"],
    outfile: "build/input.js",
    bundle: true,
    minify: true,
    sourcemap: true,
    plugins: [inlineImportPlugin(), sassPlugin(), yamlPlugin()],
    loader: {
      ".js": "jsx",
      ".woff": "file",
      ".woff2": "file",
      ".yaml": "file",
    },
  })
  .catch(() => process.exit(1));

请问哪里配置错了?是不是loader设置的问题?

解决方案

问题出在loader配置与yamlPlugin的冲突,以及动态require的处理逻辑上,修复步骤如下:

  • 移除loader中的.yaml配置项
    你同时启用了yamlPlugin()和设置了".yaml": "file" loader,两者功能冲突:yamlPlugin会把YAML解析为JS对象导入,而file loader会将YAML当作资源文件处理(返回文件路径)。直接删除loader里的.yaml配置即可。

  • 替换动态require为静态导入逻辑
    esbuild无法在构建时解析require(./${locale}.yml)这种动态路径,可改为静态导入所有语言文件再合并:

    import de from './de.yml';
    import en from './en.yml';
    import es from './es.yml';
    import fr from './fr.yml';
    import ja from './ja.yml';
    import pt from './pt.yml';
    import zh from './zh.yml';
    
    const locales = {};
    Object.assign(locales, de, en, es, fr, ja, pt, zh);
    

    若想保留循环结构,也可以用预定义的导入映射:

    const localeImports = {
      de: require('./de.yml'),
      en: require('./en.yml'),
      es: require('./es.yml'),
      fr: require('./fr.yml'),
      ja: require('./ja.yml'),
      pt: require('./pt.yml'),
      zh: require('./zh.yml'),
    };
    
    Object.values(localeImports).forEach(contents => {
      Object.assign(locales, contents);
    });
    
  • 确保yamlPlugin支持.yml后缀
    部分版本的esbuild-plugin-yaml默认只处理.yaml后缀,可显式配置支持.yml:

    yamlPlugin({ extensions: ['.yaml', '.yml'] })
    

内容的提问来源于stack exchange,提问作者Alan P.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 23:07:26