Cvetan's avatar

Requesting and bundling vendor libraries with Mix

How do I specify vendor libraries such as jQuery, Bootstrap JS, etc and them bundle them all together in one JS file?

I've gone through Laravel Mix series, but there was no mention of this type of problem.

0 likes
4 replies
Lars-Janssen's avatar

@Cvetan you can do it like this:

mix.styles([
    'public/css/vendor/normalize.css',
    'public/css/vendor/videojs.css'
], 'public/css/all.css');
Cvetan's avatar

I know how i would bundle all files, but I am wondering how to specify them as dependencies first.

Let's say I don't have them downloaded. I need to get them first somehow.

Can I do this with Laravel Mix? And when I get dependencies to bundle them.

Cronix's avatar

You do that with npm. If you look at the default package.json file that ships with laravel, you'll see it's including these packages:

"devDependencies": {
        "axios": "^0.18",
        "bootstrap": "^4.0.0",
        "cross-env": "^5.1",
        "jquery": "^3.2",
        "laravel-mix": "^2.0",
        "lodash": "^4.17.5",
        "popper.js": "^1.12",
        "vue": "^2.5.7"
}

https://github.com/laravel/laravel/blob/master/package.json

When you run npm install from the project root, it will download them and put them in /node_modules.

Then when you run npm run dev, it uses the scripts in webpack.mix.js to compile everything.

So in webpack.mix.js you could then do

mix.combine([
    'node_modules/jquery/dist/jquery.js',
    'node_modules/anotherpackage/dist/somefile.js'
], 'public/js/vendor.js');

and it will combine them, in order, into a single file in /public/js/vendor.js

D9705996's avatar

I think you are looking for the extract method of mix

https://laravel.com/docs/5.7/mix#vendor-extraction

mix.js('resources/js/app.js', 'public/js')
   .extract(['vue', 'jquery', ... ])

Then in you main layout

<script src="/js/manifest.js"></script>
<script src="/js/vendor.js"></script>
<script src="/js/app.js"></script>

This separates your application from your dependencies so you can leverage browser caching so only your app.js is changing (unless you update your npm dependencies)

Please or to participate in this conversation.