是否可以使用Webpack从es6编译为commonjs

时间:2019-01-22 13:55:48

标签: webpack commonjs es6-modules

问题是标题所暗示的-如果您已将源代码编写为es6模块(import ... from ...),然后可以使用以下命令将该源代码编译回node.js样式的commonjs模块(const ... = require(...)) Webpack?

1 个答案:

答案 0 :(得分:1)

您肯定可以。这是我的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