是否可以使用Webpack从es6编译为commonjs [英] Is it possible to compile to commonjs from es6 with webpack
问题描述
问题是标题所暗示的-如果您已将源代码编写为es6模块( import ... from ...
),然后可以将该源代码编译回node.js样式了吗?使用Webpack的commonjs模块( const ... = require(...)
)?
The question is as the title suggests- if you have written your source code as es6 modules (import ... from ...
) can you then compile this source back to node.js style commonjs modules (const ... = require(...)
) using Webpack?
推荐答案
您肯定可以.这是我的webkack.config.js,它的作用与您要求我们维护的旧项目完全相同:
You sure can. Here is my webkack.config.js which is doing exactly as you ask for a legacy project that we maintain:
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
Here I'm using an entry point for each module that I want to output and using babel-loader with an 'env' preset. This preset is exactly what you want to be using when writing in latest and greatest JS and wanting to target legacy (UMD) format: https://babeljs.io/docs/en/babel-preset-env
这篇关于是否可以使用Webpack从es6编译为commonjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!