Jun 23. 2018 · by Helge Sverre

How to use Laravel Mix in a CraftCMS project

Laravel Mix is a wrapper around webpack that makes it easy to do common stuff like compiling javascript, vue components, compiling Sass and generating sourcemaps etc, without having to battle with huge webpack config files by yourself.

To install Laravel Mix, simply run the following command (assuming you are using the Yarn package manager, which you should, because it is way faster than npm).

Installing Laravel Mix
yarn add laravel-mix cross-env

# If you insist on using NPM...
npm install laravel-mix cross-env --save

To actually use Laravel mix, we have to add some NPM scripts to our package.json file, this essentially maps a command "npm run COMMAND" to a script or a command that will be executed, think of it like a shortcut.

  "scripts": {
        "dev": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"

Here is an example webpack.mix.js file that will compile an app.js file (running it through babel so we can use the latest javascript features) as well as compile our SASS styles into a single css file

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

    .js('src/js/app.js', 'public/assets/dist/app.js')
    .sass('src/sass/app.scss', 'public/assets/dist/app.css')

And then we can run our previously defined commands like so:

How to run laravel mix scripts
npm run dev # For development
npm run watch # Watches your files for changes and compiles automatically
npm run production # For production (minifies the code etc)

Enjoy the power of webpack, without the pain and confusion.