how to create 2 different javascript files with different webpack configurations?

Viewed 24

I need to create 2 different JavaScript and CSS files, one minimized and the other one not.

I want to render the not minimized files only in Chrome, for the other browsers I want the regular minimized and compresed code.

I've tried with preset-env, changing the .babelrc file, I even tried with browserlist.

webpack.dev.js

const merge = require('webpack-merge');
const loaders = require('./webpack.loaders');
const plugins = require('./webpack.plugins');

const common = merge([{
    mode: 'development',
    entry: {
        main: [
            './src/main/resources/js/index.js'
        ],
        sitemap: [
            './src/main/resources/js/indexSiteMap.js'
        ],
        error: [
            './src/main/resources/js/error/error.js'
        ],
        icons: [
            './src/main/resources/js/fonts/google.js',
            './src/main/resources/js/fonts/features.font.js',
            './src/main/resources/js/fonts/generals.font.js'
        ]
    },
    output: {
        filename: '[name].js',
        chunkFilename: '[name].js'
    },
    devtool: 'source-map',
    optimization: {
        splitChunks: {
            cacheGroups: {
                libs: {
                    test: /node_modules/,
                    name: "libs",
                    chunks: "initial",
                    enforce: true
                }
            }
        }
    }
},
loaders.loadSass(),
loaders.loadHandlebars(),
loaders.loadReact(),
loaders.loadFileLoader(false),
loaders.loadFonts(false),
loaders.loadExpose(),
loaders.loadEslint(),
]);

module.exports = () => {
    return merge([
        common,
        plugins.clean(),
        plugins.extractCSS(false),
        plugins.copy()
    ]);
}

.babelrc

{
    "presets": ["@babel/env", "@babel/react"]
}

I get two different JavaScript files, the common.js and the modern.js

I'll load the modern -not minimized- file in chrome, otherwise I'll use the common.js file

1 Answers

You will need 2 different webpack configs, pass command line arguments like the below:

webpack --env.browser=chrome --open 'Google Chrome'

webpack --env.browser=other --open safari

And maintain 2 different webpack configs in webpack.chrome.js and webpack.other.js

and put this in webpack.config.js

module.exports = env => require(`./webpack.${env}.js`);

You will also need 2 different local servers or webpack-dev-server configs running in different ports like the below:

webpack.chrome.js

  mode: 'production',
  devServer: {
    compress: true,
    contentBase: path.join(__dirname, './dist'),
    port: 9000,
  },

webpack.other.js

  mode: 'development',
  devServer: {
    contentBase: path.join(__dirname, './dist'),
    port: 9001,
  },
Related