简体   繁体   中英

CSS Modules not applying style - next.js 13

Using next.js 13.1.1 with /app

I've been doing all of my styles through a global.css up until now, but I'm trying to migrate them into CSS Modules.

In my root layout.js , I have a Header component that imports from ./header.js . This works fine with global.css .

I've made a module ../styles/header.module.css , and I import it into ./header.js with import styles from "../styles/header.module.css"; , but then when I try to use it, for example with <h1 className={styles.big_title}> , none of the CSS is applied.

Any help would be much appreciated, I've been trying to fix this for hours. No errors occur, the CSS just doesn't apply.

// ./layout.js

import Header from "./header";
import Footer from "./footer";

import "../styles/global.css";

export default function RootLayout({ children }) {
  return (
    <html>
      <head>
          <title>SB-Wiki</title>
      </head>
      <body>
          <Header />
          <main>
              {children}
          </main>
          <Footer />
      </body>
    </html>
  );
}
/* ../styles/header.module.css */

.big_title {
    color: red;
}
// ./header.js

import styles from "../styles/header.module.css";

export default function Header() {
    return (
        <header>
            <p className={styles.big_title}>Test</p>
        </header>
    )
}

The styles display if I add import styles from "../styles/header.module.css"; to the top of a page.js but that rather defeats the point of having a root layout.js as the framework is designed this way.

The problem is with next.js . You need to create config file for next.config.js in order to properly support your CSS .

module.exports = {
   cssModules: true,
     cssLoaderOptions: {
   importLoaders: 1,
  localIdentName: "[]",
 },
};

The config file will tell the next.js to treat your CSS files as CSS

Other answers may be work, also

Try this

To use CSS Modules with Next.js , add the following to your next.config.js file to enable the CSS loader:

const withCSS = require('@zeit/next-css');
module.exports = withCSS({
  cssModules: true,
  cssLoaderOptions: {
    importLoaders: 1,
    localIdentName: '[local]___[hash:base64:5]',
  },
});

You can use it like this styles["big_title"]

// ./header.js

import styles from "../styles/header.module.css";

export default function Header() {
    return (
        <header>
            <p className={styles["big_title"]}>Test</p>
        </header>
    )
}

It could be the kebab-case. Try camelCase instead.

<p className={styles.bigTitle}>Test</p>
.bigTitle {
    color: red;
}

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