【问题标题】:Cannot use import statement outside a module with Babel configured无法在配置了 Babel 的模块外部使用 import 语句
【发布时间】:2023-04-02 01:50:01
【问题描述】:

我正在尝试将 ES6 导入与 Express Node.js 一起使用。我知道 Node.js 只支持 CommonJS,所以我用 Webpack 4 配置了 Babel,如下所示:

{
      test: /\.m?js$/,
      exclude: ['/node_modules/', /\bcore-js\b/, /\bwebpack\/buildin\b/, /@babel\/runtime-corejs3/],
      use: {
        loader: 'babel-loader',
        options: {
          babelrc : false,
          sourceType : "unambiguous",
          presets : [
            ["@babel/preset-env", {
              modules : false,
              useBuiltIns : "usage",
              corejs : {
                version : "2", 
              }
            }]
          ],
        }
      }
    },

为了测试它是否有效,我将 CommonJS require 语句更新为 ES6 imports,如下所示:

import express from "express"
import api from "api/v1/index.api.js"

const expressRouter = express.Router();

expressRouter.get('/', async function (req, res)  {
});

export default expressRouter

我相信 read this article 以上应该可以正常工作。但是在构建时,我仍然收到以下错误:

从“快递”导入快递

^^^^^^

SyntaxError: 不能在模块外使用 import 语句

我的babel-loader 没有工作,还是有其他问题?首先,并不是我所有的文件都使用 ES6 导入——有些仍然使用 CommonJS require 语句。我想我会一次在一个文件上尝试它,以确保它可以正常工作,但遗憾的是它没有。

关于看什么有什么想法吗?我使用core-js 2.6.11 因为版本3 causes problemsmini-css-extract-plugin

【问题讨论】:

    标签: javascript node.js ecmascript-6 babeljs babel-loader


    【解决方案1】:

    @babel/plugin-transform-modules-commonjs 确实为我工作,我需要一些 commonjs 库来设置测试基础设施。注意在 babel.config.js 中添加

    【讨论】:

    • 我实际上设法使用@babel/node 解决了它。在我的 package.json 中,我运行我的开发模式,如“nodemon --exec babel-node src/server.js”,它在内存中转换 server.js。
    猜你喜欢
    • 2020-10-08
    • 1970-01-01
    • 2020-06-05
    • 2022-11-02
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    相关资源
    最近更新 更多