WordPress: Laravel Mix, Sass and ES6 Modules in theme development
Tags: wordpress, tutorial, webdev, javascript
Published: 2019-04-29 18:56:14

---
title: WordPress: Laravel Mix, Sass and ES6 Modules in theme development
published: true
canonical_url: https://since1979.dev/wordpress-laravel-mix-sass-and-es6-modules-in-theme-development/
description: Learn how to get started with Sass and ES6 Modules in your WordPress themes with Laravel Mix.
cover_image: https://cdn-images-1.medium.com/max/1600/1*IK9OZbWwdkdPnWcVMm3olg.jpeg
tags: #wordpress, #tutorial, #webdev, #javascript
---

[Originally posted on my site on March 19th 2019](https://since1979.dev/wordpress-laravel-mix-sass-and-es6-modules-in-theme-development/)

### Modern (WordPress) development:

In this tutorial/article i’m going to show you a easy to setup way to start working with Sass and ES6 modules to modernize your WordPress theme development workflow. Both Sass and ES6 Modules can make your development a lot easier, help you beter organize your code and in the end keep your code much more maintainable. With this setup you can also start using new javascript features like arrow functions.

In the last section of this article i will give you some examples of using Sass and ES6 modules to show you the benefits of using these techniques.

Now before we can start using Sass and ES6 Modules we need to install something called a assats bundler. Now you may have heard of [Webpack](https://webpack.js.org/) before!? Webpack is probably the best assats bundler available, but it comes with so much options that for most developers it’s pretty hard to configure. Luckely there is a solution to that problem.

[Laravel Mix](https://laravel-mix.com/) by [Jeffrey Way](https://twitter.com/jeffrey_way) “provides a clean, fluent API for defining basic [webpack](http://github.com/webpack/webpack) build steps for your applications”. Laravel Mix was originaly created for use within Laravel applications (Hence the name), but it can easily be used for other projects like WordPress themes and plugins.

To install Laravel Mix into your project, you are going to need NPM. NPM is a CLI software Package Manager. You can use it to quickly install all kinds of packages (Javascript libraries, Css frameworks and so on) into your projects.

Ok this all sound like a lot of work. But trust me it’s not as hard as it sounds, and i’m going to show you the simpelest way.

**A minimal WordPress theme:**
As a reference to this article, and to help you follow allong i have setup a basic WordPress theme with a working setup of what i’m about to explain. You can download it from [this Github repository](https://github.com/vanaf1979/wordpress-and-laravel-mix-tutorial).

![](https://cdn-images-1.medium.com/max/1600/1*kvBbMb9_R-uuebS4IChhmQ.jpeg)

### NPM In WordPress theme development:

[NPM](https://www.npmjs.com/) or Node Package Manager is a widely used command line tool for installing Javascript and Css packages. We are going to install it so we can start using Laravel Mix, and beyond that to install javascript libraries we may need.

### Installing Npm:

NPM comes packed with NodeJs. To get started simply download and install [the latest version of NodeJs](https://nodejs.org/en/) on your maschine and this should automaticaly install NPM as well. (In some rare cases i noticed the need to restart your machine).

To check if NodeJs installed correctly open up your terminal and run the following command:

```console
$ node -v
```

This should output the NodeJs version number.

To check if NPM installed correctly as well run the following command:

```console
$ npm -v
```

This should output the NPM version number.

### Initialize NPM for your project/theme:

To initalize NPM for your project you could [run the _$ npm init_ command](http://weaintplastic.github.io/web-development-field-guide/Development/Frontend_Development/Setting_up_your_project/Setup_Dependency_Managers/Node_Package_Manager/Initialize_NPM_on_a_new_project.html) inside your theme folder and answer a bunch of questions which at the end creates a file called _package.json_ with the information you entered. But i my experience using NPM in WordPress theme’s you can just as easily create this file your self. So lets go with that option.

Create a file called _package.json_ in the root of your theme folder, and paste the [following json code](https://gist.github.com/vanaf1979/de4072a853194058ed5ef108f270549f) into it:

{% gist https://gist.github.com/vanaf1979/de4072a853194058ed5ef108f270549f %}

You can change the value’s to represent your project. Leaving the _main_, _scripts_ and _repository_ fields as they are. We are going to change the _scripts_ value later for use with Laravel Mix.

The _package.json_ file has [many options](https://docs.npmjs.com/files/package.json) which you may want to explore, but for now we have the basic setup we need.

Now that we have a _package.json_ file, we have all we need to start using MPM.

### Basic NPM commands:

NPM has [many commands an options](https://docs.npmjs.com/cli-documentation/) you can use but knowing just a handfull of commands will do for your day to day WordPress theme development. I have listed the most important commands below:

**Install an NPM package:**

```console
$ npm install _package_name_ --save
```

**Install Multiple NPM packages at once:**

```console
$ npm install package_name_one package_name_two --save
```

**Install an NPM package for development use only:**

```console
$ npm install _package_name_ --save-dev
```

**Uninstall an NPM package:**

```console
$ npm uninstall _package_name_
```

Note: The _--save_ and _--save-dev_ flags in the command’s above will make NPM list the installed package in your _package.json_ file within the "_dependencies_” or “_devDependencies_” fields. Files listed in the _dependencies_ field are packages that your project needs to run. As an example your project’s code may depend on jQuery, so it should be saved to the _dependencies_ field with the _— save_ flag. Laravel Mix on the other hand is a package we only need on our local machine to bundle our assets, so it should be saved to the _devDependencies_ field with the _— save-dev_ flag. More on this can be found in this article: “[NPMmmm #1: Dev Dependencies, Dependencies](https://medium.com/@dylanavery720/npmmmm-1-dev-dependencies-dependencies-8931c2583b0c)” by [Dylan Avery](https://medium.com/@dylanavery720).

Now that we know how to install and remove NPM packages we can install Laravel Mix to start bundeling our assets.

![](https://cdn-images-1.medium.com/max/1600/1*KFlc5IRKcYLX1SnieSLBeQ.jpeg)

### Laravel Mix in Wordpress theme development:

The [Laravel Mix](https://laravel-mix.com/) website states to be “An elegant wrapper around Webpack for the 80% use case”. Meaning that in most cases you can have all the power you need from Webpack with just a liitle bit of setup. Laravel Mix makes it realy easy to configure a Webpack setup for your project by providing a easy to understand Api.

We are going to use Laravel Mix to create a Webpack setup for our WordPress theme development. But ofcourse we need to install it into our project first.

### Installing Laravel Mix with NPM:

You can install Laravel Mix with NPM, which we just intalled and initialized for our project.

Now the Laravel Mix website say’s you only need to install the laravel-mix package from NPM, but in reality that’s not the case. You are going to need two more packages, Sass and Sass-loader for Laravel Mix to actualy work.

To install these packages _cd_ into your WordPress themes folder, if needed, and run the following commands:

```console
$ cd path/to/your/themefolder
$ npm install laravel-mix --save-dev
$ npm install sass --save-dev
$ npm install sass-loader --save-dev
```

NOTE: You can save some time by installing these three packages at once by listing them in your _npm install_ command like bellow. This will install al three packages in one go.

```console
$ npm install laravel-mix sass sass-loader --save-dev
```

When ready open up your [_package.json_](https://gist.github.com/vanaf1979/2e3a6f46003fdc42a35b1e24266434fc) file and note that NPM listed these three packages within the _devDependencies_ field like I explained before.

{% gist https://gist.github.com/vanaf1979/2e3a6f46003fdc42a35b1e24266434fc %}

NOTE: If you look at your files you’l notice that NPM has created a folder called _node_modules_ in the root of your theme where it stores the files of your installed packages. If you are using Git to version control your WordPress theme you will want to add this folder to your _.gitignore_ file.

Now that we have Laravel Mix installed we have to create a configuration file called _webpack.mix.js_. This file will hold our custom configuration.

### Configuring webpack.mix.js:

A core concept of using Laravel Mix, or any other bundler, is that we have a source and an output. Meaning that we write our code in a source file/folder and the bundler creates processed/bundled/minified files as it’s output that we can reference in our WordPress theme.

If you have a look at the files of our example theme you’l notice that we have a _src_ directory, and inside it we have subfolders for _scss_, _img_ and _js_ to organize our code. The _js_ and _scss_ directories contain a _app.js_ and _app.scss_ respectivaly which will serve as our entry-points (sources) for Laravel Mix.

![](https://cdn-images-1.medium.com/max/1600/1*pNFGdY9SNpvbi2UiKOkoLQ.png)

We also have a _public_ folder which has the same structure as our _src_ folder with one small diffrense being in the _public_ folder we have a _css_ subfolder instead of a _scss_ folder because we are going to bundle our ._scss_ files to ._css_ files so that all browsers can handle them. The _public_ folder serves as out output folder. The files in this folder will be added to the theme.

![](https://cdn-images-1.medium.com/max/1600/1*9SSEYbj6ZwZ5icmKZXZFKg.png)

Now to configure Laravel Mix to meet our custom file structure we have to create a file called webpack.mix.js in the root of our WordPress theme folder and copy & paste the [following code](https://gist.github.com/vanaf1979/d8a7e4a91aa92ef190214c863a9912d6):

{% gist https://gist.github.com/vanaf1979/d8a7e4a91aa92ef190214c863a9912d6 %}

With this configuration we import Laravel Mix and chain four functions to the Mix object and tell Webpack to do the following:

- **.js()** Find a file called _app.js_ within the _src/js_ folder, bundle it and place the output in a file called _app.js_ within the _public/js_ folder.
- **.sass()** Find a file called _app.scss_ within the _src/scss_ folder, bundle it and place the output in a file called _app.css_ within the _public/css_ folder.
- **.copyDirectory()** Find a folder called _src/img_ and copy it to the _public_ folder.
- **.options()** Tell webpack not to change any urls in our css.

With this _webpack.mix.js_ file we now have a working configuration for Laravel Mix that we could start using.

NOTE: Laravel Mix has a lot more options then shown in this example which you can read up on in the [laravel mix documentation](https://laravel-mix.com/docs/4.0/installation). But for now we have al we need to start using it.

Now we need a way to run Laravel Mix so it can do it’s magic.

### Configuring package.json to run Laravel Mix.

To run Laravel Mix with our custom configuration you could run the [following command](https://gist.github.com/vanaf1979/1c6e453df300eeb2842c650863ea6ecb) in your Cli. But remembering this command or copy pasting it each time we need it is not realy a workable solution.

{% gist https://gist.github.com/vanaf1979/1c6e453df300eeb2842c650863ea6ecb %}

Luckaly we created a _package.json_ file before which has the option of creating NPM command shortcuts within a scripts object like shown below

Copy [lines 14 till 20 below](https://gist.github.com/vanaf1979/90d6ca8054992556357ff987b678747e) and add them to your _package.json_ file:

{% gist https://gist.github.com/vanaf1979/90d6ca8054992556357ff987b678747e %}

With these scripts added to our _package.json_ file we now have three handy commands we can use to work with Laravel Mix.

```console
$ npm run dev
```

This command will process and bundle our files for development use.

```console
$ npm run watch
```

This command will de the same as _npm run dev_ but will keep running and watch for file changes. If any of our files changes it will automaticaly process and bundle our files again.

NOTE: To stop the _npm run watch_ process you can type _ctrl + c_ in your terminal window.

```console
$ npm run production
```

This command will process, bundle and minify our files for use in production a.k.a your live website.

To test our setup run the _npm run dev_ command listed above, and if all goes well you should be presented with a list of files that were processed. If not, most errors that accour will have something to do with a wrong file path. You can scroll to the top of the error message and it will likely tell you it can’t find a certain file. Or you can referense the Example theme.

![](https://cdn-images-1.medium.com/max/1600/1*Ijza36DEhYkVNXpXCszpsA.jpeg)

### Sass/Scss in WordPress theme development:

[Sass](https://sass-lang.com/) hase many options that will help you write better css and structure your codebase to be more maintainable. You can find all the options within the [Sass documentiation](https://sass-lang.com/guide). But i will give you some basic examples to show you how to better structure your css.

NOTE: Sass comes in two flavours. Sass and Scss. De difrence between these two is the file extentions and the syntax used. Now i personaly like the Scss flavour, so i’m gonne use that for these examples. The documentation will always list both so you can choose wich one you like best. If you want to use the sass version, change your file names to have the .sass file extention.

**Importing files:** One of the most usefull features of Sass is the fact that you can split your code into several files, and then import these files into your Bundlers entry point.

In the example WordPress theme we use _src/scss/app.scss_ as our entry point for Laravel Mix (See the webpack.mix.js file), We only use this file to import other .scss files so that Laravel Mix bundles these into our output _app.css_ file.

{% gist https://gist.github.com/vanaf1979/b1acb69bf2df471ac3b117a7cc75c703 %}

In the [example Above](https://gist.github.com/vanaf1979/b1acb69bf2df471ac3b117a7cc75c703) we:

*   Import four files that come from an NPM package called “purecss”. Packages from NPM are located within the _node_modules_ folder, hence we start our url’s with the ~ character which is a shortcut to the node_modules fiolder.
*   We import a external Google fonts css file. Note that these files are not included in our output bundle, but our downloaded by the browser.
*   We import a custom scss file from within a components folder called _html-body.scss._

If you have a look at the example theme you’l notice a _components_ folder within the _src/scss_ folder. You are free to make up your own file structure, but as an example i use this folder to store scss files for each of my webpage compomnents.

So if i have a slider at the top of my webpage is will create a file _slider.scss_ in my components folder. Put all css related to that slider there, and import it into my _app.scss_ entry point. I’ll repeat these steps for all other sections of my webpage.

**Nesting selectors:**
Below is an example on nesting css selectors. Meaning that one selector/group can contain other selectors. The Sass compiler within Laravel Mix will process this syntax and output normal css from [this code](https://gist.github.com/vanaf1979/488b8c0985e1aea494564c4cc8dffcb4).

{% gist https://gist.github.com/vanaf1979/488b8c0985e1aea494564c4cc8dffcb4 %}

The code above will output css for the nav, nav ul, nav ul li and nau ul li a as you would find in normal css.

**Variables:**
Sass also makes it possible to create variables within your code. [Below](https://gist.github.com/vanaf1979/b950aa8636aee6dbf2e20549291e5021) is a simple example, but i would recommend you create a seperate variables.scss files, as shown in _src/scss/common/variables.scss_ in the example WordPress theme. and import that at the top of your _app.scss_ entry point. You can then access these variables from any other imported .scss file.

{% gist https://gist.github.com/vanaf1979/b950aa8636aee6dbf2e20549291e5021 %}

This is just a fraction of the usefull things Sass brings to css development. I highly recommend you take a look at the [Saas documentation](https://sass-lang.com/guide) for other stuff like Mixins and Inheritance.

![](https://cdn-images-1.medium.com/max/1600/1*XF9tn_1nLA_x5L7zf-L1iw.jpeg)

### ES6 Modules in WordPress theme development:

ES6 Modules are a great way to organize your WordPress theme’s javascript code. And to prevent nasty spaghetti code files.

[Chris Coyier](https://twitter.com/chriscoyier) has a great article over at Css-Tricks.com: “[How Do You Structure JavaScript? The Module Pattern Edition](https://css-tricks.com/how-do-you-structure-javascript-the-module-pattern-edition/)” that explains the use of Modules in-depth. But i’ll give a small example below.

The basic principle is to create seperate files for diffrent sections of your site. So to continue the example i gave earlier, if i have a slider at the top of my site i will create a file called slider.js in the src/js/components/slider folder. In the slider.js file i will create a object called Slider and add my code to that object. At the end of the file i will export the object as a module.

In my app.js entry point file i will import the Slider object/module and initialize it at Dom Ready.

Have a look at the [example below](https://gist.github.com/vanaf1979/5761c393475b564e2ed1a3b29e9cdac9):

{% gist https://gist.github.com/vanaf1979/5761c393475b564e2ed1a3b29e9cdac9 %}

Here we create a javascript object called Example which holds three functions. At the end of the file we export this Example object as a Module with _export default Example_.

We can now import the module we just created with _import Example from ‘./components/example.js’_ as shown in the [app.js file below](https://gist.github.com/vanaf1979/e8aaaabcea10c74b40cb3fa22b061ede). After we have imported it we call the modules _init()_ function at Dom Ready.

{% gist https://gist.github.com/vanaf1979/e8aaaabcea10c74b40cb3fa22b061ede %}

NOTE: In the code above you can see that i’m using a arrow function as the callback for _$().ready(_ **_() =>{}_** _)_. Arrow functions are not supported by all browsers, but i can use it here anyway becouse Laravel Mix (Using [Babel](https://babeljs.io/)) will convert this back to plain javascript that all browsers can understand. So you see you can start using modern javascript syntaxt now becouse of Laravel Mix and Webpack.

You can repeat these steps and create more modules for other parts of your website and import these into your _app.js_ entry point as well as [shown below](https://gist.github.com/vanaf1979/fca8286bdc733456632caa492f4c266f):

{% gist https://gist.github.com/vanaf1979/fca8286bdc733456632caa492f4c266f %}

**Importing NPM Packages within your javascript:**
Since we have NPM up and running for our WordPress theme we could also use it to add other javascript libraries to out code.

For example. let’s say you want to use the [moment.js](https://momentjs.com/) library in your code. You could add a new scripts tag to your page, or enqueuue it properly from within your _functions.php_ or you could now simply run the following command:

```console
$ npm install moment --save
```

This will download and add moment.js to your project (and _package.json_ file). And you can now use it in a module like [shown below](https://gist.github.com/vanaf1979/7629e98a27038394560bcd867131f91c):

{% gist https://gist.github.com/vanaf1979/7629e98a27038394560bcd867131f91c %}

I hope that these examples make sense and show how you can better organize and code your WordPress theme’s css and javascript.

### All done!?

If you have a configuration that you are happy with and want to use it in another project, you dont have to repeat all these steps. Just copy your _package.json_ and _webpack.mix.js_ files to your new project. Adjust them to meet your needs and run _npm install_. which will make NPM install all packages listed in your _package.json_ file.

This is also true if you share your code with others, directly or via Github. You don’t have to share all the packages, just the _package.json_ file. Someone else can just run _npm install_, and NPM will download all the packages again.

You can find a basic WordPress theme with the configurations mentioned above in [this Github repository](https://github.com/vanaf1979/wordpress-and-laravel-mix-tutorial).

I hope you liked this article and found something that will help you make better WordPress themes.

I know we only covered the basics here. I will be publishing an additional article with some more in-depth Laravel Mix options soon. So stay tuned. Follow me on Twitter: [Vanaf1979](http://bit.ly/2RCf9eF), [my website Since1979.dev](https://since1979.dev) or here on Dev.to.

Happy Theming…