简体   繁体   中英

How can I use Node.js CommonJS modules in ES6 import/export modules using babel or webpack?

I'm sorry if this is a duplicate (I looked hard using the search tool but nothing came close). Anyone has any ideas how to transpile Node.js CommonJS modules so they can be used within an ES6 import/export project?

I know there's @babel/plugin-transform-modules-commonjs which transpiles ES6 modules into CommonJS form, but I think I'm in need of the opposite. The reason I need this is I have a config file written using Node's module.exports syntax that needs to be imported within a React project built with babel using ES6 modules, but I get a Uncaught TypeError: Cannot assign to read only property 'exports' of object error. Any ideas would be greatly appreciated.

Here's my babelrc.js file:

module.exports = {
  presets: ['@babel/preset-env', '@babel/preset-react'],
  plugins: [
    ['@babel/plugin-proposal-class-properties', { loose: true }],
    ['@babel/plugin-transform-runtime', { regenerator: true }],
    '@babel/plugin-syntax-dynamic-import',
    '@babel/plugin-proposal-optional-chaining'
  ],
  env: {
    production: {
      plugins: [
        [
          "transform-react-remove-prop-types",
          { removeImport: true }
        ],
      ]
    }
  }
}

And my webpack config babel loader rule:

{
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          use: [
            {
              loader: 'babel-loader',
              options: {
                cacheDirectory: true,
                cacheCompression: false,
                envName: isModeProduction ? 'production' : 'development'
              }
            }
          ]
        },

Thanks to @Thomas Sablik's comment, I found out this was a known webpack issue .

And after poking round and looking up this error, I found this answer on another Stack Overflow which helped me fix it by adding "sourceType": "unambiguous" to my babel configuration. https://stackoverflow.com/a/56283408/2942765

Thank you Thomas.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM