【问题标题】:How can I use Node.js CommonJS modules in ES6 import/export modules using babel or webpack?如何使用 babel 或 webpack 在 ES6 导入/导出模块中使用 Node.js CommonJS 模块?
【发布时间】:2021-11-27 00:43:21
【问题描述】:

如果这是重复的,我很抱歉(我用搜索工具仔细看了看,但没有任何结果)。任何人都知道如何转换 Node.js CommonJS 模块,以便在 ES6 导入/导出项目中使用它们?

我知道有 @babel/plugin-transform-modules-commonjs 将 ES6 模块转换为 CommonJS 形式,但我认为我需要相反的。我需要这个的原因是我有一个使用 Node 的 module.exports 语法编写的配置文件,需要在使用 ES6 模块使用 babel 构建的 React 项目中导入,但我收到 Uncaught TypeError: Cannot assign to read only property 'exports' of object 错误。任何想法将不胜感激。

这是我的 babelrc.js 文件:

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 }
        ],
      ]
    }
  }
}

还有我的 webpack config babel loader 规则:

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

【问题讨论】:

  • 没必要。您可以使用 ES6 通过 Node.js 导入 CJS 模块。
  • 我试过了,但它给出了我在描述中列出的错误。
  • 这能解决您的问题吗? github.com/webpack/webpack/issues/4039 好像是 babel 的问题。
  • 是和不是 ????我不知道这是一个 webpack 问题,所以非常感谢你的澄清。我尝试替换 module-exports -> exports 但这并没有解决问题(它破坏了其他东西)。但是,您为我指出了正确的方向,经过一番挖掘,我发现设置 babel 的 sourceType: ambigous 解决了这个错误。随意复制并粘贴此链接作为答案,我很乐意将其标记为已接受的答案,因为您帮助我找到了解决方案。
  • 不,应该避免仅链接的答案,我现在没有时间写解释。您可以回答自己的问题或等待其他人。

标签: javascript node.js webpack babeljs es6-modules


【解决方案1】:

感谢@Thomas Sablik 的评论,我发现这是known webpack issue。

在四处寻找这个错误之后,我在另一个 Stack Overflow 上找到了这个答案,它通过在我的 babel 配置中添加 "sourceType": "unambiguous" 来帮助我修复它。 https://stackoverflow.com/a/56283408/2942765

谢谢托马斯。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    相关资源
    最近更新 更多