'How to conditionally import a SCSS stylesheet in Next.js?

I'm trying to load a stylesheet depending on the environment, in _app.js:

if (process.env.NODE_ENV === 'production' ) {
  import '../styles/globals-production.scss'
} else {
  import '../styles/globals-staging.scss'
}

But getting this error in the console: Syntax error: 'import' and 'export' may only appear at the top level

Any ideas on how I can do this with Next.js?



Solution 1:[1]

In my case I wanted to import rtl bootstrap so I added a selector to toggle the import. You will need a way to add a custom attribute to the html tag.

If you are using Next I recommend nextjs custom document: https://nextjs.org/docs/advanced-features/custom-document

Then in your style.scss wrap the import with the custom attribute selector, ex:

[dir='rtl'] {
  @import '~bootstrap/dist/css/bootstrap.rtl.min';
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zahema