webpack5打包报错“import may appear only with 'sourceType: module' ”?

需求:将包含ES6+的代码打包成es5代码,且兼容IE10及以上

遇到的问题,打包时报错:
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)
image.png

源代码:

import axios from 'axios';

const url = 'http://xxx.com';
export async function doTest () {
  let obj = {
    name: '张三',
    age: 23
  };
  let newObj = {
    ...obj,
    score: 89
  };
  let asyncTime = await new Promise(function (resolve) {
    setTimeout(function () {
      resolve(150);
    }, 1500);
  });
  console.log('asyncTime', asyncTime);
  axios.get(url)
    .then(res => {
      console.log('res', res.data);
    })
    .catch(err => {
      console.error('请求出错', err);
    });
}

webpack.build.config.js

const path = require('path');

const filename = 'atest.min.js';
module.exports = {
  mode: 'production',
  entry: {
    index: './aTest.js'
  },
  output: {
    filename,
    path: path.resolve(__dirname, './dist'),
    libraryTarget: 'umd',
    libraryExport: 'default',
    library: 'aTest',
    environment: {
      // 是否使用箭头函数
      arrowFunction: false,
      // 是否使用const、let定义变量
      const: false,
      // 是否使用对象解构语法
      destructuring: false,
      // 是否支持使用for of遍历
      forOf: false,
      // 是否支持可选链('obj?.a'或'obj?.()')
      optionalChaining: false
    }
  },
  // 构建目标
  target: ['web', 'es5'],
  module: {
    rules: [
      {
        test: /\.js$/,
        // include: /(node_modules|bower_components)/,
        use: {
          loader: "babel-loader",
          options: {
            presets: [
              '@babel/preset-env'
            ],
            plugins: ["@babel/plugin-transform-runtime"]
          }
        }
      }
    ]
  },
  optimization: {
    minimize: true, // 混淆压缩
  }
};

package.json

{
  "name": "a-bug-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --config webpack.build.config.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.27.2"
  },
  "devDependencies": {
    "@babel/cli": "^7.18.10",
    "@babel/core": "^7.19.0",
    "@babel/plugin-transform-runtime": "^7.18.10",
    "@babel/preset-env": "^7.19.0",
    "babel-loader": "^8.2.5",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server": "^4.11.0"
  }
}

特殊说明:
不允许使用下面这种形式来引入polyfill

entry: {
  index: ['babel-polyfill','./aTest.js']
},

原因:打包出来后的js需要给用户使用,如果用户使用时他们打包的配置中也用统一方式添加了babel-polyfill,在使用时会报重复引入babel-polyfill的错误

阅读 6.2k
1 个回答

大概看了下:这种写法是会带来错误的

export async function doTest () {

}

改成下面这种,应该就可以

export function doTest () {
    return new Promise()
}

===补充===

  • webpack.build.config.js
    @babel/plugin-transform-runtime注释掉

    module: {
    rules: [
      {
        test: /\.js$/,
        // include: /(node_modules|bower_components)/,
        use: {
          loader: "babel-loader",
          options: {
            presets: [
              '@babel/preset-env'
            ],
            // plugins: ["@babel/plugin-transform-runtime"]
          }
        }
      }
    ]
    },
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏