Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.JS using CSS Modules not working as expected

I'm migrating my CRA to Next and having issues with locally scoped CSS modules.

File Tree

.
├── Headline.js
├── profile.png
└── welcome.module.css

Code

import React from 'react';
import "./welcome.module.css" 

function Headline() {
  return (
        <section className={'headliner-container'}>
          <div className={'main-headline'}></div>
        </section>
    );
}

export default Headline;

I realize I can get this to work by doing import styles from "./welcome.module.css" and referencing via className={styles["classNameHere"]}, but how does that scale for large migration projects? I want to use the CSS I had with minimal modification to my JSX.

Update:

I found out I could add this and disable all the weird opinions Next is throwing into my CSS structure:

module.exports = withCSS({
  cssLoaderOptions: {
    url: false
  }
})

Any opposition to this in my next config?

like image 552
Ryan Avatar asked Oct 18 '25 05:10

Ryan


1 Answers

I ran into the same issue you had when I was migrating our UI component library. You might be able to do something like this. import styles from "./welcome.module.css". This allows you to do minimum work on the CSS side while still be able to leverage CSS Modules down the road.

:global {
 .headliner-container {
   margin: 0 20px;
 }
}

I do suggest you at least use a component scope class name on the top-level DOM node if possible so CSS override will less likely to happen. I don't know how pure CSS Module might handle it since I used Less for my situation.

import React from 'react';
import styles from "./welcome.module.css" 

function Headline() {
  return (
        <div className={styles.headLineWrapper}>
           <section className={'headliner-container'}>
             <div className={'main-headline'}></div>
           </section>
        </div> 
    );
}

export default Headline;
/*LESS code */
.head-line-wrapper {
  :global {
   .headliner-container {
     margin: 0 20px;
   }
  }
}
like image 97
Andrew Zheng Avatar answered Oct 19 '25 22:10

Andrew Zheng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!