奇怪的 @babel/runtime 错误:Module parse failed: 'import' and 'export' may appear only with 'sourceType: module' (1:0)

错误

ERROR in ./node_modules/@babel/runtime/helpers/esm/typeof.js 1:0
Module parse failed: 'import' and 'export' may appear only with 'sourceType: module' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders        
> export default function _typeof(obj) {
|   "@babel/helpers - typeof";
|
 @ ./node_modules/@material-ui/utils/esm/getDisplayName.js 1:0-56 49:6-13
 @ ./node_modules/@material-ui/utils/esm/index.js 12:0-61 12:0-61
 @ ./node_modules/@material-ui/core/esm/SvgIcon/SvgIcon.js 6:0-52 131:12-26
 @ ./node_modules/@material-ui/core/esm/SvgIcon/index.js 1:0-36 1:0-36
 @ ./src/App/TitleBar.tsx 8:0-48 41:100-107
 @ ./src/App/index.tsx 12:0-34 28:101-109
 @ ./src/index.tsx 4:0-24 5:50-53

尝试修改babel-loader选项,无效,因为这好像本来就是默认值,preset-typescript不支持 ESM 语法吗?webpack不支持ESM语法吗?莫名其妙!

module.exports = {
    "$babel_loader": {
        "loader": "F:\\Github\\react-dev-server\\node_modules\\babel-loader",
        "options": {
            "sourceType": "module", // 尝试解决 @babel/runtime 编译错误,无效。替换esm下文件并修改package.json字段type为commonjs即可
            "plugins": [
                "F:\\Github\\react-dev-server\\node_modules\\@babel\\plugin-transform-runtime",
                "F:\\Github\\react-dev-server\\node_modules\\@babel\\plugin-proposal-class-properties"
            ],
            "presets": [
                [
                    "F:\\Github\\react-dev-server\\node_modules\\@babel\\preset-env",
                    {
                        "targets": {
                            "esmodules": false
                        }
                    }
                ],
                [
                    "F:\\Github\\react-dev-server\\node_modules\\@babel\\preset-typescript"
                ],
                [
                    "F:\\Github\\react-dev-server\\node_modules\\@babel\\preset-react"
                ]
            ],
        }
    },
    "$css_loader": "F:\\Github\\react-dev-server\\node_modules\\css-loader",
    "$style_loader": "F:\\Github\\react-dev-server\\node_modules\\style-loader",
    "$file_loader": "F:\\Github\\react-dev-server\\node_modules\\file-loader"
};

解决办法

进入 node_modules\@babel\runtime\helpers 目录,把 applyDecoratedDescriptor.js 等100个文件复制到 esm 目录下,用 cjs 代码替换掉 esm 代码,并删除 esm 目录下的 package.json 文件或修改其字段:

{
  "type": "module"
}

修改为:

{
  "type": "commonjs"
}
posted @ 2023-04-19 16:33  develon  阅读(1231)  评论(1编辑  收藏  举报