【问题标题】:Server side rendered imported CSS module not as expected服务器端渲染导入的 CSS 模块与预期不符
【发布时间】:2017-03-20 09:44:38
【问题描述】:

很抱歉,如果以前报告过此问题,我已尝试在 Google 上找到解决方案并在此处搜索问题,但找不到描述我的问题的内容。

我在 React 的控制台中收到一个错误,提示客户端和服务器标记不匹配并且校验和失败。这会导致 FOUC。

考虑以下来源:

// MyComponent.scss
.myComponent {
   background: black;
}



// MyComponent.js
import styles from './MyComponent.scss';

const MyComponent = () => <div className={styles.myComponent}>Hello</div>;

export default MyComponent;

在客户端上,这按预期工作,styles.myComponent 将呈现为 MyComponent-myComponent-[hash],如您所料。

但是,在服务器上 styles.myComponent 未定义,因此省略了类名,这就是导致控制台错误的原因,因为 DOM 结构不匹配。我已经记录了样式对象,看起来服务器上有一个locals 对象,这是我找到渲染组件名称的地方。例如

styles: {
   locals: {
     myComponent: 'MyComponent-myComponent-[hash]'
   }
}

我不知道从哪里开始寻找为什么导入的 css 模块对象在客户端和服务器上看起来不同。

【问题讨论】:

    标签: reactjs server-side-rendering css-modules


    【解决方案1】:

    原来是糟糕的 Webpack 配置。

    我正在使用 extract-text-plugin 将 CSS 提取到单独的文件中。我分别为客户端和服务器包共享了模块规则。 A 为客户端代码创建了一个ExtractTextPlugin 的实例,并使用该实例的extract 函数来包装共享模块规则。在客户端配置中,我在插件链中指定了此实例,但在服务器包中,我在插件链中使用了new ExtractTextPlugin(),看来这就是导致断开连接的原因。

    我最终编写了一个包装函数来为每个捆绑配置复制 CSS 规则。

    【讨论】:

      猜你喜欢
      • 2017-07-02
      • 2016-04-09
      • 1970-01-01
      • 2021-06-18
      • 2023-04-09
      • 2018-05-08
      • 2021-10-20
      • 1970-01-01
      相关资源
      最近更新 更多