Search code examples
webpackcommonjses6-modules

Is it possible to compile to commonjs from es6 with webpack


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?


Solution

  • 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()
        ]
    };
    

    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