webpack - 为什么 babel-loader 失败但 babel-node 可以很好地混合 ES 导入和 CJ 模块?
问题描述
我的项目中有文件同时使用 CJSrequire
和 ESimport
语法,如下所示:
const multer = require('multer');
import multerS3 from './multer-s3-storage-engine.js';
const ExpressRouter = require('express').Router();
....
....
module.exports = ExpressRouter;
我知道我们不应该将这些混合在一起,但我认为babel
这就是为了将所有内容转换为工作。
在开发中,我用babel-node
这样的方式启动dev
版本:
"dev": "babel-node -r dotenv/config src/server.js"
以上工作正常,我所有的混合 CJS 和 ES 文件都工作。但是,当涉及到生产构建时,Webpack 失败并抛出此错误:
throw new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id);
Error: ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: 262
262
指的module.exports = ExpressRouter;
是我上面代码中的部分。
构建的Webpack 5
配置文件是这样的:
const path = require('path')
const webpack = require('webpack')
const nodeExternals = require('webpack-node-externals');
const utils = require('./utils');
const isProduction = process.env.NODE_ENV === 'production';
module.exports = {
entry: {
server: utils.resolve('/src/server.js')
},
target: 'node',
// This tells the server bundle to use Node-style exports
output: {
path: utils.resolve('/dist'),
filename: '[name].js',
sourceMapFilename: isProduction ? '[name].[hash].js.map' : '[name].js.map',
libraryTarget: 'commonjs2'
},
node: {
// Need this when working with express, otherwise the build fails
__dirname: false,
__filename: false,
},
externals: nodeExternals({
allowlist: [
/^vue-meta*/,
/\.(css|sass|scss|vue|html)$/,
]
}),
optimization: {
minimize: isProduction ? true : false,
minimizer:[
(compiler) => ({
terserOptions: {
compress: {drop_console: isProduction ? true : false},
format: {
comments: isProduction ? false : true
},
}
})
]
},
module: {
rules: [
{
// Transpiles ES6-8 into ES5
test: /\.m?jsx?$/,
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,
corejs: {
version: "3.9.0",
proposals: true
},
}
]
],
}
}
},
]
}
};
在package.json
我也有以下配置:
"babel": {
"presets": [
"@babel/preset-env"
],
"sourceType": "unambiguous"
}
为什么它与babel-node
而不是一起工作的原因是什么babel-loader
?
解决方案
推荐阅读
- python - 我的不和谐机器人刚刚坏了,我不知道为什么(discord.py)
- android - 适用于 Android 的 IntelliJ IDEA 上的 Gradle 同步错误
- c# - 如何使用参数 ASP.NET MVC 调用 Ajax 数据表?
- node.js - 如何将 jwt 从 swift 客户端传递到 node.js 服务器
- unix - AWK 在 shell 内打印意外的换行符或字符串结尾
- flutter - 提供者对象在现有构建期间请求重建
- typescript - 如何在 Typescript 类中使用 yield
- python - 通过 python 子进程运行多线程 C 程序
- css - 我试图创建一个页脚保持底部,但它不工作
- javascript - 使用 Webpack 4 获取捆绑的两个脚本标签