sassnext.jsscss-mixins

Using scss mixins with nextJs


I I've got the following next.config.js setup:

const path = require('path')
const withSass = require('@zeit/next-sass');
module.exports = withSass({
    cssModules: true
})
module.exports = {
    sassOptions: {
        includePaths: [path.join(__dirname, 'styles')]
    },
}

and I'm importing a global scss file using:

import '../styles/main.scss';

In this main.scss file, I'm using some mixins like:

@mixin wrapper() {
  ...
  @media screen and ($max-hd) {
    width: calc(100% - 6em);
  }
  @media screen and ($max-md) {
    width: calc(100% - 2em);
  }
}

where both max-hd and max-md are variables from another scss file:

$max-md: 'max-width: (#{$break-md - 1px})';
$max-hd: 'max-width: (#{$break-hd - 1px})';

If I use the variable ${max-hd} in as content in the same wrapper mixin, it prints the right value:

content: "max-width: (1739px)";

But the media queries seem to be completely ignored. I'm having a hard time debugging, as this is my first time with Next.js and I can't find the exported styles (google developer tools throws me back to the actual scss, which looks correct).

Does anyone have any idea of what I'm doing wrong?


Solution

  • This is how I use scss with my next js project:

    1. Install sass
    npm install --save-dev sass
    
    

    (or npm i sass if you compile your code on the server).

    1. I created a root directory named scss, in it I have my variables, mixins etc. For example:

    breakpoints.scss

    $screen-sm-min: 640px;
    $screen-md-min: 768px;
    $screen-lg-min: 1024px;
    $screen-xl-min: 1280px;
    
    @mixin sm {
      @media (min-width: #{$screen-sm-min}) {
        @content;
      }
    }
    
    @mixin md {
      @media (min-width: #{$screen-md-min}) {
        @content;
      }
    }
    
    @mixin lg {
      @media (min-width: #{$screen-lg-min}) {
        @content;
      }
    }
    
    @mixin xl {
      @media (min-width: #{$screen-xl-min}) {
        @content;
      }
    }
    
    
    1. Then I use scss modules like this:

    MyComponent.module.scss:

    
    @import '/scss/breakpoints';
    
    .image {
      position: relative;
      
    
      @include lg {
        position: fixed;
      }
    }
    
    1. in my component, I import the styles and use them as described here: https://beta.nextjs.org/docs/styling/css-modules

    There are more options here: https://beta.nextjs.org/docs/styling/sass