简体   繁体   中英

How to choose what css file to be imported using next.js?

I'm now trying to choose which css file to apply using next.js.

I have two css files, one for pc, and one for mobile.

Currently, I am importing css file like below:

// _app.tsx

import "../styles/globals.css";  // pc styling css
// import "../styles/globals_mobile.css";  // mobile styling css

function MyApp({ Component, pageProps }: AppProps) {
  // ... remaining code
}

Now I have mobile css styling file, and I have isMobile boolean variable which identifies that the device is pc or mobile from AppProps .

But I couldn't find a way how to import css file dynamically.

The below is pseudocode, it is not actually working:

// _app.tsx

import pcStyling from "../styles/globals.css";  // it is NOT actually imported.
import mobileStyling from "../styles/globals_mobile.css";  // it is NOT actually imported.


function MyApp({ Component, pageProps }: AppProps) {
  if (pageProps.isMobile) apply mobileStyling;
  else apply pcStyling;

  // ...
}

Is there an option I am able to choose?

Since your styles are static, you can put them inside the public folder. And inject the proper link to them inside <Head> component.

This should look similar to this:

// _app.tsx
import Head from 'next/head';

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <>
      <Head>
        <link rel="stylesheet" href={`/styles/globals${pageProps.isMobile ? '_mobile' : ''}.css`} />
      </Head>
      {'rest of your components'}
    </>
  );
}

The code above assumes that inside public folder there is /styles/globals.css & /styles/globals_mobile.css files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM