Ralph David Abernathy
Ralph David Abernathy

Reputation: 5518

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?

Upvotes: 5

Views: 5840

Answers (2)

Ron Newcomb
Ron Newcomb

Reputation: 3302

The javascript import statement must appear at top level, but the import() "function" is probably what you wanted there.

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

Upvotes: 1

Zahema
Zahema

Reputation: 1415

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';
}

Upvotes: 2

Related Questions