Import SASS variables into Material UI theme with NextJS

Tags: , , , ,



In my project I have the following files:

materialTheme.ts

import { createMuiTheme, Theme } from "@material-ui/core/styles";

const theme: Theme = createMuiTheme({
  palette: {
    primary: { main: "#209dd2", contrastText: "#fff" },
    secondary: { main: "#81B44C", contrastText: "#fff" },
  },
});

export default theme;

palette.scss

$primary: #209dd2;
$secondary: #81b44c;
$contrast: #fff;

:export {
  primary: $primary;
  secondary: $secondary;
  contrast: $contrast;
}

I want to de-duplicate these files. I thought I could import the variables from palette.scss into materialTheme.ts but Next.JS throws an error about only importing global CSS into _app.tsx

materialTheme.ts (not working)

import { createMuiTheme, Theme } from "@material-ui/core/styles";

import palette from "./palette.scss";

const theme: Theme = createMuiTheme({
  palette: {
    primary: { main: palette.primary, contrastText: palette.contrast },
    secondary: { main: palette.secondary, contrastText: palette.contrast },
  },
});

export default theme;

Is there any way I can make NextJS ignore this error just for materialTheme.ts and correctly import the variables?

I’d imagine I could definite const theme inside my _app.tsx and then import palette.scss there but ideally I’d like to maintain separate files for the theme and the app.

Alternatively, is there any pattern in which I can import the Javascript variables into the SCSS file or the SCSS variables into the Javascript file whilst adhering to this no global CSS rule?

Answer

You can rename palette.scss to palette.module.scss to follow the CSS modules naming convention used by Next.js. This tells Next.js that the Sass file is locally scoped and can be imported anywhere in your app.



Source: stackoverflow