Next.JS 使用 CSS 模块无法按预期工作

Rya*_*yan 0 javascript css reactjs next.js

我正在将我的 CRA 迁移到 Next 并且遇到本地范围的 CSS 模块问题。

文件树

.
??? Headline.js
??? profile.png
??? welcome.module.css
Run Code Online (Sandbox Code Playgroud)

代码

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

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

export default Headline;
Run Code Online (Sandbox Code Playgroud)

我意识到我可以通过执行import styles from "./welcome.module.css" 和引用 via来实现这一点className={styles["classNameHere"]},但是对于大型迁移项目来说,这如何扩展?我想使用对 JSX 进行最少修改的 CSS。

更新:

我发现我可以添加这个并禁用所有奇怪的意见 Next 扔进我的 CSS 结构:

module.exports = withCSS({
  cssLoaderOptions: {
    url: false
  }
})
Run Code Online (Sandbox Code Playgroud)

在我的下一个配置中有任何反对意见吗?

And*_*eng 5

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;
 }
}
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)
:global {
 .headliner-container {
   margin: 0 20px;
 }
}
Run Code Online (Sandbox Code Playgroud)

  • 嘿。我尝试了这个并收到错误“选择器“:global”不是纯的(纯选择器必须包含至少一个本地类或id)” - 为此,我需要在 next.config 中使用“cssLoaderOptions”吗? (2认同)