Webpack+Babel报错:'import'和'export'仅能在sourceType: module下使用
问题:Webpack+Babel编译报错:'import' and 'export' may appear only with 'sourceType: module'
本人对Babel经验有限,运行JS应用时出现如下报错,若从webpack配置中移除"./src/index.js",报错会消失但应用无法正常运行。
报错信息
ERROR in ./node_modules/@babel/runtime/regenerator/index.js 1:0 Module parse failed: 'import' and 'export' may appear only with 'sourceType: module' (1:0) File was processed with these loaders: * ./node_modules/babel-loader/lib/index.js You may need an additional loader to handle the result of these loaders. > import _typeof from "@babel/runtime/helpers/typeof"; | | // TODO(Babel 8): Remove this file. @ ./src/index.js 3:0-61 19:54-78 21:11-35 66:61-85 67:9-33 ERROR in Error: Child compilation failed: Module parse failed: 'import' and 'export' may appear only with 'sourceType: module' (1:0) File was processed with these loaders: * ./node_modules/babel-loader/lib/index.js You may need an additional loader to handle the result of these loaders. > import _typeof from "@babel/runtime/helpers/typeof"; | | // TODO(Babel 8): Remove this file.: SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' (1:0) ModuleParseError: Module parse failed: 'import' and 'export' may appear only with 'sourceType: module' (1:0) File was processed with these loaders: * ./node_modules/babel-loader/lib/index.js You may need an additional loader to handle the result of these loaders. > import _typeof from "@babel/runtime/helpers/typeof"; | | // TODO(Babel 8): Remove this file. - NormalModule.js:976 handleParseError [wolf3d-readyplayerme-threejs-boilerplate]/[webpack]/lib/NormalModule.js:976:19 ERROR in Error: Child compilation failed: Module parse failed: 'import' and 'export' may appear only with 'sourceType: module' (1:0) File was processed with these loaders: * ./node_modules/babel-loader/lib/index.js You may need an additional loader to handle the result of these loaders. > import _typeof from "@babel/runtime/helpers/typeof"; | | // TODO(Babel 8): Remove this file.: SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' (1:0) ModuleParseError: Module parse failed: 'import' and 'export' may appear only with 'sourceType: module' (1:0) File was processed with these loaders: * ./node_modules/babel-loader/lib/index.js You may need an additional loader to handle the result of these loaders. > import _typeof from "@babel/runtime/helpers/typeof"; | | // TODO(Babel 8): Remove this file. - NormalModule.js:976 handleParseError [wolf3d-readyplayerme-threejs-boilerplate]/[webpack]/lib/NormalModule.js:976:19 - child-compiler.js:131 [wolf3d-readyplayerme-threejs-boilerplate]/[html-webpack-plugin]/lib/child-compiler.js:131:18 - Compiler.js:551 finalCallback [wolf3d-readyplayerme-threejs-boilerplate]/[webpack]/lib/Compiler.js:551:5 1 ERROR in child compilations (Use 'stats.children: true' resp. '--stats-children' for more details) webpack 5.74.0 compiled with 4 errors and 11 warnings in 16857 ms
当前webpack.config.js配置
const webpack = require("webpack"); const path = require("path"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const HtmlWebpackPlugin = require("html-webpack-plugin"); module.exports = (env) => { const isProd = env && env.prod; const config = { mode: isProd ? "production" : "development", performance: { hints: false }, entry: ["babel-polyfill", "./src/index.js"], plugins: [ new webpack.DefinePlugin({ DEVELOPMENT: !isProd, }), new webpack.ProvidePlugin({ process: 'process/browser', }), new HtmlWebpackPlugin({ template: "./src/index.js", }), new CopyWebpackPlugin({ patterns: [{ from: "src/assets", to: "assets" }], }), new HtmlWebpackPlugin({ title: isProd ? "Production" : "Development", meta: { viewport: "width=device-width, initial-scale=1, shrink-to-fit=no, maximum-scale=1.0, user-scalable=no", }, }), ], output: { filename: "[name].js", path: path.resolve(__dirname, "dist"), }, resolve: { fallback: { util: require.resolve("util/") } }, module: { rules: [ { test: /\.(glsl|vs|fs|vert|frag)$/, use: ["raw-loader", "glslify-loader"], }, { test: /\.js$/, use: { loader: "babel-loader", options: { compact: false, presets: [["@babel/preset-env"]], plugins: [ ['@babel/plugin-transform-runtime', { "regenerator": true } ], "@babel/plugin-proposal-optional-chaining", "@babel/plugin-syntax-nullish-coalescing-operator", ], }, }, }, ], }, }; if (!isProd) { config.devtool = "eval"; } return config; };
解决方案
1. 修复HtmlWebpackPlugin的错误配置
你重复实例化了HtmlWebpackPlugin,且第一个实例把JS文件(./src/index.js)作为template参数,这会导致插件试图将JS文件编译为HTML,触发额外的子编译流程,直接引发报错。
合并成一个正确的配置:
new HtmlWebpackPlugin({ title: isProd ? "Production" : "Development", meta: { viewport: "width=device-width, initial-scale=1, shrink-to-fit=no, maximum-scale=1.0, user-scalable=no", }, // 若需要自定义HTML结构,创建一个HTML模板文件(比如./src/index.html)并指定这里,不要用JS文件当模板 // template: "./src/index.html" }),
2. 让babel-loader处理@babel/runtime模块
默认情况下webpack不会处理node_modules下的文件,但@babel/runtime里的ES模块需要被转译。修改babel-loader规则,加入对@babel/runtime的处理:
{ test: /\.js$/, // 包含src目录和@babel/runtime,确保这些文件被babel转译 include: [path.resolve(__dirname, "src"), path.resolve(__dirname, "node_modules/@babel/runtime")], use: { loader: "babel-loader", options: { compact: false, presets: [["@babel/preset-env", { // 可选:根据目标浏览器配置,让babel更精准转译 targets: "> 0.25%, not dead" }]], plugins: [ ['@babel/plugin-transform-runtime', { "regenerator": true } ], "@babel/plugin-proposal-optional-chaining", "@babel/plugin-proposal-nullish-coalescing-operator" // 替换原有的syntax插件,proposal版本才能实际转译语法 ], }, }, },
3. 替换废弃的babel-polyfill
babel-polyfill已被废弃,改用core-js和regenerator-runtime替代:
- 先安装依赖:
npm install core-js@3 regenerator-runtime --save
- 修改webpack的entry配置:
entry: ["core-js/stable", "regenerator-runtime/runtime", "./src/index.js"],
- 同时在
@babel/preset-env中配置相关选项:
presets: [["@babel/preset-env", { targets: "> 0.25%, not dead", useBuiltIns: "usage", // 自动按需引入polyfill corejs: 3 // 对应安装的core-js版本 }]],
内容的提问来源于stack exchange,提问作者v1rus96
相关产品推荐
相关产品推荐

