Inject sass global variables from next.config.js - sass env variables

Add global variable to sass compiler with-next-sass - This official next.js example demonstrates how to use Next.js' built-in Global Sass/Scss imports and Component-Level Sass/Scss modules support. This stackoverflow answears helped me. Nextjs has built in sapport for sass. To use component isolated .sass or .scss files you need to install sass. npm install sass To configure sass compiler you can use sassOptions in next.config.js. nextjs.org/#customizing-sass-options For instance, if you want to load assets from styles like @font-face src and have different locations on prod and dev environments, you can do the following: In next config set assetPrefix depending on the environment. Then, add sassOptions variable. // next.config.js module.exports = (phase) => { // when started in development mode `next dev` or `npm run dev` const isDev = phase === PHASE_DEVELOPMENT_SERVER; // when `next build` or `npm run build` is used const isProd = phase === PHASE_PRODUCTION_BUILD; const assetPrefix = isProd ? '/prod' : '/'; const sassOptions = { prependData: `$prefix: "${assetPrefix}";`, } ... // Other configuration return { ... sassOptions }; } In .scss files now you can use this prefix variable to prepend import paths. @font-face { font-family: 'Open-Sans'; src: url("#{$prefix}fonts/OpenSans-Regular.ttf");

Apr 29, 2025 - 15:21
 0
Inject sass global variables from next.config.js - sass env variables

Add global variable to sass compiler

with-next-sass - This official next.js example demonstrates how to use Next.js' built-in Global Sass/Scss imports and Component-Level Sass/Scss modules support.

This stackoverflow answears helped me.

Nextjs has built in sapport for sass. To use component isolated .sass or .scss files you need to install sass.

npm install sass

To configure sass compiler you can use sassOptions in next.config.js. nextjs.org/#customizing-sass-options

For instance, if you want to load assets from styles like @font-face src and have different locations on prod and dev environments, you can do the following:

In next config set assetPrefix depending on the environment. Then, add sassOptions variable.

// next.config.js

module.exports = (phase) => {
  // when started in development mode `next dev` or `npm run dev`
  const isDev = phase === PHASE_DEVELOPMENT_SERVER;
  // when `next build` or `npm run build` is used
  const isProd = phase === PHASE_PRODUCTION_BUILD;

  const assetPrefix = isProd ? '/prod' : '/';

  const sassOptions = {
    prependData: `$prefix: "${assetPrefix}";`,
  }

  ... // Other configuration

  return {
    ...
    sassOptions
  };
}

In .scss files now you can use this prefix variable to prepend import paths.

@font-face {
  font-family: 'Open-Sans';
  src: url("#{$prefix}fonts/OpenSans-Regular.ttf");