CSS 模块的 React 服务器端渲染
React Server side rendering of CSS modules
目前CSS使用React组件的做法好像是使用webpack的style-loader加载到页面中。
import React, { Component } from 'react';
import style from './style.css';
class MyComponent extends Component {
render(){
return (
<div className={style.demo}>Hello world!</div>
);
}
}
通过这样做,样式加载器会将 <style>
元素注入到 DOM 中。但是,<style>
不会在虚拟 DOM 中,因此如果进行服务器端渲染,<style>
将被省略。这导致页面具有 FOUC.
是否有任何其他加载方法 CSS modules 在服务器端和客户端都有效?
您可以使用 webpack/extract-text-webpack-plugin
。这将创建一个独立的可重新分发的样式表,您可以从您的文档中引用。
你可以看看isomorphic-style-loader。加载器就是专门为解决这类问题而创建的。
然而,要使用它,您必须使用加载程序提供的 _insertCss()
方法。文档详细说明了如何使用它。
希望对您有所帮助。
对我来说,我正在使用 Webpack 加载器 css-loader 在同构应用程序中实现 CSS 模块。
在服务器端,webpack 配置如下:
module: {
rules: [
{
test: /\.(css)$/,
include: [
path.resolve(__dirname, '../src'),
],
use: [
{
// Interprets `@import` and `url()` like `import/require()` and will resolve them
loader: 'css-loader/locals',
options: {
modules: true,
localIdentName: '[name]__[local]--[hash:base64:5]'
}
},
],
},
]
}
在客户端,webpack 配置如下所示
{
// Interprets `@import` and `url()` like `import/require()` and will resolve them
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[name]__[local]--[hash:base64:5]'
}
},
当然,如果你用的是SASS,你需要用sass-loader
把scss编译成css,postcss-loader
可以帮忙添加 autoprefixer
.
目前CSS使用React组件的做法好像是使用webpack的style-loader加载到页面中。
import React, { Component } from 'react';
import style from './style.css';
class MyComponent extends Component {
render(){
return (
<div className={style.demo}>Hello world!</div>
);
}
}
通过这样做,样式加载器会将 <style>
元素注入到 DOM 中。但是,<style>
不会在虚拟 DOM 中,因此如果进行服务器端渲染,<style>
将被省略。这导致页面具有 FOUC.
是否有任何其他加载方法 CSS modules 在服务器端和客户端都有效?
您可以使用 webpack/extract-text-webpack-plugin
。这将创建一个独立的可重新分发的样式表,您可以从您的文档中引用。
你可以看看isomorphic-style-loader。加载器就是专门为解决这类问题而创建的。
然而,要使用它,您必须使用加载程序提供的 _insertCss()
方法。文档详细说明了如何使用它。
希望对您有所帮助。
对我来说,我正在使用 Webpack 加载器 css-loader 在同构应用程序中实现 CSS 模块。
在服务器端,webpack 配置如下:
module: {
rules: [
{
test: /\.(css)$/,
include: [
path.resolve(__dirname, '../src'),
],
use: [
{
// Interprets `@import` and `url()` like `import/require()` and will resolve them
loader: 'css-loader/locals',
options: {
modules: true,
localIdentName: '[name]__[local]--[hash:base64:5]'
}
},
],
},
]
}
在客户端,webpack 配置如下所示
{
// Interprets `@import` and `url()` like `import/require()` and will resolve them
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[name]__[local]--[hash:base64:5]'
}
},
当然,如果你用的是SASS,你需要用sass-loader
把scss编译成css,postcss-loader
可以帮忙添加 autoprefixer
.