我的项目中有文件同时使用 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
?