Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 566
Fergie Avatar asked Oct 29 '25 08:10

Fergie


1 Answers

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

like image 94
BlueWater86 Avatar answered Oct 31 '25 11:10

BlueWater86



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!