【问题标题】:Can't import const enums in webpack with babel project无法使用 babel 项目在 webpack 中导入 const 枚举
【发布时间】:2021-12-06 09:12:17
【问题描述】:

我正在开发一个使用 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",

【问题讨论】:

  • 你介意分享一个可重现的回购吗?
  • 那个外部包是开源项目吗?也许你可以分享它的名字。我想重现该问题并尝试我想到的解决方法。最好的办法是用实际的包装试试。
  • 不,它不是一个开源项目。 ts-loader 解决了我的问题。感谢您的评论。

标签: reactjs typescript webpack babel-loader


【解决方案1】:

根据这个thread,涉及插件的创建者,babel 不会转译.d.ts 文件,因此无法从那里获取枚举。唯一的选择似乎是migrating 你的配置使用ts-loaderinclude 具有枚举声明的.d.ts 文件

tsconfig

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

【讨论】:

    猜你喜欢
    • 2016-06-15
    • 2021-06-30
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    相关资源
    最近更新 更多