[英]Cannot use import statement outside a module with Babel configured
I am trying to use ES6 imports with Express Node.js.我正在尝试将 ES6 导入与 Express Node.js 一起使用。 I know that Node.js supports CommonJS only so I have configured Babel with Webpack 4 like such:
我知道 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",
}
}]
],
}
}
},
As a test to see if it works I updated my CommonJS require
statements into ES6 import
s like such:作为测试它是否有效,我将 CommonJS 的
require
语句更新为 ES6 import
,如下所示:
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
I believe having read this article that the above should just work.我相信在阅读了这篇文章后,上面的内容应该可以正常工作。 But on build, I still get the following error:
但是在构建时,我仍然收到以下错误:
import express from "express"
从“快递”进口快递
^^^^^^
^^^^^^
SyntaxError: Cannot use import statement outside a module
SyntaxError:不能在模块外使用 import 语句
Is my babel-loader
not working, or is there some other issue going on?我的
babel-loader
不工作,还是有其他问题? Firstly not all my files are using ES6 imports - some are still using CommonJS require
statements.首先,并不是我所有的文件都使用 ES6 导入——有些仍然使用 CommonJS 的
require
语句。 I thought I'd try it on one file at a time to ensure it works which sadly it does not.我想我会一次尝试一个文件,以确保它可以正常工作,但遗憾的是它没有。
Any ideas on what to look at?关于看什么的任何想法? I am using
core-js 2.6.11
because version 3
causes problems with mini-css-extract-plugin
我正在使用
core-js 2.6.11
,因为版本3
导致mini-css-extract-plugin
出现问题
@babel/plugin-transform-modules-commonjs did work for me where I needed the some commonjs lib to be used for setting up the test infrastructure. @babel/plugin-transform-modules-commonjs 确实为我工作,我需要一些 commonjs 库来设置测试基础设施。 Note to add it in babel.config.js
注意在 babel.config.js 中添加
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.