thoward
thoward

Reputation: 369

Laravel Mix common chunk and vendor chunk

I'm building a multipage app with Laravel v5.5 and using Laravel Mix v1.6.2 to compile my assets. I am defining an entry point for each page. I'm extracting vendor modules to a seperate vendor output chunk:

mix.js('resources/assets/js/page1.js', 'public/js')
.js('resources/assets/js/page2.js', 'public/js')
.extract('vue');

What I also want to accomplish is having modules I've written, which are shared between multiple (2 or more) pages/entry-points, automatically extracted to a separate chunk (e.g. commons.js). I can do that with this:

mix.webpackConfig({
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
          name: "commons",
          filename: "js/commons.js",
          minChunks: 2
        })
    ]
});

But this doesn't work together with mix.extract(). I've seen the examples here. But unsure of how to accomplish this in Laravel Mix.

Ideally the output would be something like:

js/
 |- page1.js
 |- page2.js
 |- commons.js
 |- vendor.js

Upvotes: 2

Views: 3483

Answers (1)

thoward
thoward

Reputation: 369

After having a look though the Laravel Mix source, I realised that the array provided to mix.js().extract() is just being used to create entry points and so rather than use extract() I just used custom config to specify entry points for my node_modules that are being used everywhere, with entry point name matching the chunk name.

let mix = require('laravel-mix');
let webpack = require('webpack');

mix.js('resources/assets/js/page1.js', 'public/js')
    .js('resources/assets/js/page2.js', 'public/js');

mix.sass('resources/assets/sass/app.scss', 'public/css');

mix.webpackConfig({
    entry: {
        vendor: [
            'vue',
            'axios',
            'lodash',
            'promise-polyfill',
            'setasap'
        ]
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            names: ["commons", "vendor"],
            filename: 'js/[name].js',
            minChunks: 2
        })
    ]
});

This results in 4 output files:

js/
 |- page1.js
 |- page2.js
 |- commons.js
 |- vendor.js

Upvotes: 5

Related Questions