DEV Community

Cover image for Inject sass global variables from next.config.js - sass env variables
vavilov2212
vavilov2212

Posted on

1

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
Enter fullscreen mode Exit fullscreen mode

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
  };
}
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

Warp.dev image

Warp is the #1 coding agent.

Warp outperforms every other coding agent on the market, and gives you full control over which model you use. Get started now for free, or upgrade and unlock 2.5x AI credits on Warp's paid plans.

Download Warp

Top comments (0)

Redis image

Short-term memory for faster
AI agents

AI agents struggle with latency and context switching. Redis fixes it with a fast, in-memory layer for short-term context—plus native support for vectors and semi-structured data to keep real-time workflows on track.

Start building

👋 Kindness is contagious

Discover fresh viewpoints in this insightful post, supported by our vibrant DEV Community. Every developer’s experience matters—add your thoughts and help us grow together.

A simple “thank you” can uplift the author and spark new discussions—leave yours below!

On DEV, knowledge-sharing connects us and drives innovation. Found this useful? A quick note of appreciation makes a real impact.

Okay