Using Laravel Mix Without Laravel
Laravel ships with the
laravel-mix npm module installed. Laravel Mix is a wrapper around Webpack that simplifies the process of compiling your web assets (which seems to be useful for "80% of the use cases").
Setting Up Your Project
Let's assume we are starting from scratch; a new empty folder. We'll want to initialize our npm directory as follows.
You can accept all the defaults of the
npm init command. This will create a
package.json in your directory.
Install Laravel Mix
Next, we need to install the following node packages:
npm install laravel-mix cross-env
You can expect this command to take several minutes to install and compile all of the required dependencies. (It will also install
webpack as it is a dependency of
Now, create the
webpack.mix.js file, which serves as a configuration to specify via
laravel-mix what you want
webpack to do. Places this contents inside it:
let mix = require('laravel-mix');
This will compile your SCSS assets (
style.scss) to CSS (
style.css) and place it inside the
app.js) also into the
dist folder (
app.js). (Make sure that you do place those files
app.js inside the
assets folder (or specify what files you'd like to compile.
npm Commands to Your
The only piece we are missing is a command to tell Webpack to process our operations. Place this command inside the
"scripts" dictionary of your
package.json file (that should have been created when you ran the
npm init command.
"dev": "npm run development",
"development": "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",
"watch-poll": "npm run watch -- --watch-poll",
"hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
"prod": "npm run production",
"production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
Compile Your Assets
Now you can compile your assets for development (no minifying but faster).
npm run development
Or for production (slower but minified and less file size).
npm run production
Note that you can use
npm run dev and
npm run prod as shorthands instead of
npm run development and
npm run production.
You can also run the
watch command while you are editing your assets during development — Laravel Mix will re-compile everything you make changes to one of your asset files and save. This will make your development experience even better. Just remember to compile in
production before deploying your application so your assets get minified.
npm run watch
You are all set!