Seperate Babel Polyfills from Main Code when bundling

569 views Asked by At

I am using Webpack and Babel. Babel is generating a single file main.js in my output directory with all the polyfills added along side my js files. I would like to separate the polyfills from the main code into two different files. polyfills.js and main.js.

Is this possible?

My current webpack config looks like:


module.exports = {
    entry: ['@babel/polyfill' ,'./src/index.js'],
    output: {
         path: path.resolve('./dist'),
         filename: 'main.js',
    },
    mode: 'development',
    devtool: 'source-map',
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
        compress: true,
        port: 9000
    },
    optimization: {
        minimize: true,
    },
    module: {
    rules: [
        {
            test: /\.m?js$/,
            exclude: [/node_modules/],
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/preset-env'],
                    plugins: ['@babel/plugin-transform-runtime']
                }
            }
        }
    ]
    }
  };

and my BabelRC looks like:

{
    "presets": [
        ["@babel/preset-env", {
            "useBuiltIns": "entry",
            "debug":false,
            "corejs": "3.6.5",
            "targets": {
                "chrome": "38"
            }
        }]
    ],
    "compact": true
}
1

There are 1 answers

3
Sofien Joulak On

yes it's possible

just use SplitChunksPlugin like

module.exports = {
    entry: ["@babel/polyfill",'./src/index.js'],
    output: {
        path: path.resolve('./dist'),
    },
    mode: 'development',
    devtool: 'source-map',
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
        compress: true,
        port: 9000
    },
    optimization: {
        minimize: true,
        splitChunks: {
            cacheGroups: {
                vendor: {
                    test: /[\\/]node_modules[\\/](@babel[\\/]polyfill)[\\/]/,
                    name: 'vendor',
                    chunks: 'all',
                    enforce: true
                },
            },
        }       
    },
    module: {
    rules: [
        {
            test: /\.m?js$/,
            exclude: [/node_modules/],
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/preset-env'],
                    plugins: ['@babel/plugin-transform-runtime']
                }
            }
        }
    ]
    },
};

More info here https://v4.webpack.js.org/plugins/split-chunks-plugin/#optimizationsplitchunks

You can use BundleAnalyzerPlugin if you want to analyse & visualize the content of your build