Extract css in node_modules using laravel mix

Laravel mix is the default assets compilation package comes with laravel 5.4. It use webpack to compile assets. Using Mix you can define simple webpack build steps without going deep into webpack configrations.

You can also use laravel mix in your other projects with some little tweaks.

Your laravel installation should have following structure

  • /webpack.mix.js – mix configration file
  • /resources/assets/ – entry folder
  • /public/assets/ – output folder

Laravel mix supports extracting js vendor scripts to a separate file using mix configurations. The extract method accepts an array of all libraries or modules that you wish to extract into a vendor.js file.

mix.js('resources/assets/js/app.js', 'public/js')
   .extract(['lodash','bootstrap','bootstrap-datepicker'])

But unfortunately for style files it doesn’t work like that .  we have to include urls separately.

mix.styles([
    'node_modules/bootstrap/dist/css/bootstrap.css',
    'node_modules/bootstrap-datepicker/dist/css/bootstrap-datepicker.css',
    'node_modules/font-awesome/css/font-awesome.css'
], 'public/assets/css/app.css');

To avoid that what you can do is import the CSS files in a SCSS file and use it in mix config.

If you are using a IDE it auto suggest the URL and you don’t have to browse through long list of folders in node_modules.

/resources/assets/sass/app.scss

@import url('/node_modules/bootstrap/dist/css/bootstrap.css')
@import url('/node_modules/bootstrap-datepicker/dist/css/bootstrap-datepicker.css')
@import url('/node_modules/font-awesome/css/font-awesome.css')

And use it mix configuration file.

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

Final mix config file should look as below

/webpack.mix.js

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

mix.js('resources/assets/js/app.js', 'public/core')
    .extract(['jquery', 'bootstrap','bootstrap-datepicker']);

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

 

Let me know if you are familiar with more suitable way to Extract CSS in laravel mix.