TypeScript“声明”字段必须首先由 @babel/plugin-transform-typescript 进行转换

ANi*_*120 5 babeljs

当尝试构建我的反应应用程序时,我收到错误TypeScript 'declare' fields must first be transformed by @babel/plugin-transform-typescript.。但我不明白为什么,因为我正在使用@babel/preset-typescript. 我该如何修复这个错误?

//craco.config.js
const path = require("path");
const CracoAlias = require("craco-alias");

module.exports = {
  webpack: {
    configure: {
      module: {
        rules: [
          {
            type: "javascript/auto",
            test: /\.mjs$/,
            include: /node_modules/,
          },
        ],
      },
    },
  },
  plugins: [
    {
      plugin: CracoAlias,
      options: {
        source: "tsconfig",
        baseUrl: "./src",
        tsConfigPath: "./tsconfig.path.json",
      },
    },
  ],
  style: {
    postcss: {
      plugins: [require("tailwindcss"), require("autoprefixer")],
    },
  },
  babel: {
    presets: [
      "@babel/preset-typescript",
      "@babel/preset-react",
      "@babel/preset-env",
    ],
    plugins: [["glsl", {"loose": true}]],
  },
};

Run Code Online (Sandbox Code Playgroud)

完整错误说明:

TypeScript 'declare' fields must first be transformed by @babel/plugin-transform-typescript.
If you have already enabled that plugin (or '@babel/preset-typescript'), make sure that it runs before any plugin related to additional class features:
 - @babel/plugin-proposal-class-properties
 - @babel/plugin-proposal-private-methods
 - @babel/plugin-proposal-decorators
Run Code Online (Sandbox Code Playgroud)

这是有问题的班级:

TypeScript 'declare' fields must first be transformed by @babel/plugin-transform-typescript.
If you have already enabled that plugin (or '@babel/preset-typescript'), make sure that it runs before any plugin related to additional class features:
 - @babel/plugin-proposal-class-properties
 - @babel/plugin-proposal-private-methods
 - @babel/plugin-proposal-decorators
Run Code Online (Sandbox Code Playgroud)

小智 9

当我将 React Native 项目升级到 0.64.2 时,我遇到了同样的错误。为了解决这个问题,我必须更改 babel.config.js 文件,如下所示:

module.exports = {
  presets: [
    'module:metro-react-native-babel-preset',
    ['@babel/preset-typescript', {allowDeclareFields: true}],
  ],
};
Run Code Online (Sandbox Code Playgroud)

我猜想在你的 craco.config.js 中,这将映射到以下内容(尽管我不知道 craco 是什么,所以只是根据与 babel.config.js 的相似性进行猜测):

    presets: [
      ["@babel/preset-typescript", {allowDeclareFields: true}],
      "@babel/preset-react",
      "@babel/preset-env",
    ],
  },
Run Code Online (Sandbox Code Playgroud)

  • 我需要将此设置添加到“@babel/plugin-transform-typescript”插件中来解决该问题。由于某种原因,将设置添加到预设没有效果。 (4认同)