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

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Image of Datadog

Keep your GPUs in check

This cheatsheet shows how to use Datadog’s NVIDIA DCGM and Triton integrations to track GPU health, resource usage, and model performance—helping you optimize AI workloads and avoid hardware bottlenecks.

Get the Cheatsheet

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay