Ryan
Ryan

Reputation: 1232

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?

Upvotes: 3

Views: 23722

Answers (1)

Andrew Zheng
Andrew Zheng

Reputation: 2858

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

Upvotes: 15

Related Questions