Search code examples
webpackbabeljscommonjs

Weird error with CommonJs under Webpack4 + babel8 + coreJs@3


This is the entrance:

// index.js
const {test} = require('./handle')
test()

This is a commonjs module

// handle.js
module.exports = {
  test() {
    console.log('>>>>>   handle get trigger')
    console.log(typeof [])
  }
}

Compile success,then I got this error while running

Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'

If I remove console.log(typeof []) from handle.js, the error disappear.

my babel config is:

{
                test: /\.jsx?$/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ["@babel/preset-env"],
                        plugins: [
                            [
                                "@babel/plugin-transform-runtime",
                                {
                                    "corejs": 3
                                }
                            ],
                            "@babel/plugin-syntax-dynamic-import"
                        ]
                    }
                },
                include: /src/
            },

The error also disapper when I use ES6 module to write this.


Solution

  • @babel/plugin-transform-runtime adds import to my files! So it become a mix use of ES6Module and CommonJs ! That cause the problem!!!!!!

    So,we can only use Es6module or add a babel plugin @babel/plugin-transform-modules-commonjs