miguel.nz

Shared variables between JS and CSS using Laravel Mix and Stylus

December 25, 2019   |   1 minute read.

Laravel Mix is a Webpack Wrapper created for Laravel. However, it works also with any other web application, including WordPress. Laravel Mix let us write modern Javascript, use CSS Frameworks such as Stylus amont other things. Is dead simple to use, specially if you’re coming from the world of Grunt or Gulp.

Sharing variables between CSS and JS files will becomes very handy when working with Media Queries (@media). Often our breakpoints are working just fine with CSS. Having JS functions relying on these breakpoints would help us to keep our code clean and easy to maintain.

First, we have a mediaQueries.js file which stores our breakpoints. Let’s say we will store it under our resources folder.

mediaQueries.js

exports = module.exports = mediaQueries;

function mediaQueries() {
  return {
    'desktop-layout': 960,
    'tablet-layout': 641,
    'mobile-layout': 640
  }
};

In order to get these breakpoints as variables we will define them on our webpack.mix.js file. Stylus has a Javascript API which help us to define and interact with JS files.

webpack.mix.js

let mix = require('laravel-mix');
let mediaQueries = require('./resources/mediaQueries'); // Route to mediaQueries.js, stored under resources.

//...

var screenSizes = function(style){
  style.define('desktop-layout', mediaQueries()['desktop-layout']);
  style.define('tablet-layout', mediaQueries()['tablet-layout']);
  style.define('mobile-layout', mediaQueries()['mobile-layout']);
};

//...

mix.stylus(
  'style.styl', 
  'style.css', {
    use: [
      screenSizes
    ]
});

//...

Using screenSizes on Stylus

screenSizes will become very useful to help us define our media queries. My approach to get them to work is this:

mediaqueries.styl

desktop   = 'screen and (min-width: '+unit(desktop-layout, 'px')+')'
tablet    = 'screen and (min-width: '+unit(tablet-layout, 'px')+') and (max-width:'+(unit(desktop-layout, 'px')  - 1px) +')'
mobile    = 'screen and (max-width: '+unit(mobile-layout, 'px')+')'

Now I can easily call a mediaquerie by typing:

@media mobile

Which will be compiled into:

@media screen and (max-width: 640px)

Using screenSizes on JS

You can now easily import the mediaQueries.js using import:

import mediaQueries from './mediaQueries';