无法使用 babel 项目在 webpack 中导入常量枚举

Can't import const enums in webpack with babel project

我正在开发一个使用 create-react-app 构建的 React 项目,后来我们弹出并修改了很多 webpack 配置。现在我很难从外部库中导入 const enums。我无法控制那个外部包。它具有在其 d.ts 文件中定义的常量枚举。

我试过 babel-plugin-use-const-enum babel 插件和预设。它对我也没有帮助。

我的 webpack 配置:

.....
.....
{
  test: /\.(js|mjs|jsx|ts|tsx)$/,
  include: [paths.appSrc],
  loader: require.resolve("babel-loader"),
  options: {
    customize: require.resolve("babel-preset-react-app/webpack-overrides"),
    plugins: [
        [require.resolve("babel-plugin-const-enum"), { transform: "constObject" }],
        [require.resolve("@babel/plugin-transform-typescript"), { isTSX: true, optimizeConstEnums: true }],
        [require.resolve("@babel/plugin-transform-react-jsx")],
        [require.resolve("@babel/plugin-proposal-class-properties"), { loose: true }],
        [require.resolve("@babel/plugin-proposal-nullish-coalescing-operator")],
        [require.resolve("@babel/plugin-proposal-optional-chaining"), { isTSX: true }],
        [require.resolve("@babel/plugin-transform-arrow-functions")],
        [require.resolve("@babel/plugin-proposal-private-methods"), { loose: true }],
        [
          require.resolve("babel-plugin-named-asset-import"),
          {
            loaderMap: {
              svg: {
                ReactComponent: "@svgr/webpack?-svgo,+titleProp,+ref![path]",
              },
            },
          },
        ],
    ],
    presets: ["@babel/preset-env"],
  },
},
.....
.....

我的 tsconfig:

{
  "compilerOptions": {
    "typeRoots": ["./typings", "node_modules/@types"],
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "noEmit": true,
    "jsx": "react",
    "downlevelIteration": true
  },
  "exclude": ["dist/**/*"],
}

问题是构建成功了,但我遇到了所有 const 枚举导入的运行时问题,如下所示

Uncaught TypeError: Cannot read properties of undefined (reading '<ConstEnumName>').

包版本:

"@babel/core": "^7.11.6",
"babel-loader": "^8.1.0",
"typescript": "^3.9.7",
"webpack": "^4.44.2",

根据此 thread, where the plugin's creator is involved, babel does not transpile .d.ts files, making it impossible to get enums from there. The only option seems to be migrating your config to use ts-loader and include .d.ts 具有枚举声明的文件

tsconfig

{
  ...
  "exclude": ["dist/**/*"],
  "include": ["node_modules/[external_library]/**/*.d.ts"],
}