问题正如标题所暗示的那样 - 如果你已经将源代码编写为es6模块(import ... from ...
),那么你可以使用Webpack将这个源代码编译回node.js样式的commonjs模块(const ... = require(...)
)吗?
你肯定可以。这是我的webkack.config.js它完全按照您对我们维护的遗留项目的要求进行操作:
var path = require("path");
var webpack = require('webpack');
var HardSourceWebpackPlugin = require("hard-source-webpack-plugin");
module.exports = {
node: { fs: 'empty' },
entry: {
polyfill: "./wwwroot/js/helpers/polyfill.js",
budget: ["babel-polyfill", "./wwwroot/js/pages/budget.js"],
sirtflow: ["babel-polyfill", "./wwwroot/js/pages/sirtflow.js"],
apps: ["babel-polyfill", "./wwwroot/js/pages/apps.js"],
settings: ["babel-polyfill", "./wwwroot/js/pages/settings.js"]
},
output: {
publicPath: "/js/",
path: path.join(__dirname, "/wwwroot/js/webpack/"),
filename: "[name].js"
},
resolve:
{
alias: {
'handlebars': 'handlebars/dist/handlebars.js'
}
},
devtool: false,
module: {
rules: [
{
test: /.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
['env', {
modules: false,
useBuiltIns: 'usage'
}]
]
}
}
}
]
},
plugins: [
new HardSourceWebpackPlugin()
]
};
在这里,我为要输出的每个模块使用入口点,并使用带有"env"预设的 babel-loader。此预设正是您在使用最新和最好的 JS 编写并希望面向传统 (UMD) 格式时要使用的预设:https://babeljs.io/docs/en/babel-preset-env