我正在尝试使用 SSR 将 CSS 添加到我在 React 中构建的组件中,但我无法这样做。
我看过的东西:
- https://www.npmjs.com/package/isomorphic-style-loader
- https://cssinjs.org/server-side-rendering/?v=v10.0.0-alpha.22
- 网络包加载器
但这个过程都不简单或明确提及。我尝试了很多的是同构加载器,它似乎很有前途,但是在我的 CSS 文件中设置它后它给出了一些模糊的错误:
意外令牌 (1:0( 您可能需要适当的加载程序来处理此文件类型。
这是我的样板包 - https://github.com/alexnm/react-ssr
如何将样式添加到我的 React SSR 代码中。
更新
const dev = process.env.NODE_ENV !== "production";
const path = require( "path" );
const { BundleAnalyzerPlugin } = require( "webpack-bundle-analyzer" );
const FriendlyErrorsWebpackPlugin = require( "friendly-errors-webpack-plugin" );
const plugins = [
new FriendlyErrorsWebpackPlugin(),
];
if ( !dev ) {
plugins.push( new BundleAnalyzerPlugin( {
analyzerMode: "static",
reportFilename: "webpack-report.html",
openAnalyzer: false,
} ) );
}
module.exports = {
mode: dev ? "development" : "production",
context: path.join( __dirname, "src" ),
devtool: dev ? "none" : "source-map",
entry: {
app: "./client.js",
},
resolve: {
modules: [
path.resolve( "./src" ),
"node_modules",
],
},
module: {
rules: [
{
test: /.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
},
],
},
output: {
path: path.resolve( __dirname, "dist" ),
filename: "[name].bundle.js",
},
plugins,
};
下面的配置使CSS工作
安装的软件包:
babel-plugin-dynamic-import-node, babel-plugin-css-modules-transform, mini-css-extract-plugin, css-loader, style-loader
索引.js
require( "babel-register" )( {
presets: [ "env" ],
plugins: [
[
"css-modules-transform",
{
camelCase: true,
extensions: [ ".css", ".scss" ],
}
],
"dynamic-import-node"
],
} );
require( "./src/server" );
webpack.config.js
rules: [
{
test: /.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
},{
test: /.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
'css-loader'
],
},
]
在 webpack 配置中,添加了以下插件
new MiniCssExtractPlugin({
filename: "styles.css",
}),
在 server.js 中,在 htmlTemplate 的 head 中添加了以下代码。
<link rel="stylesheet" type="text/css" href="./styles.css" />
用法
import "./../App.css";
<h2 className="wrapper">F1 2018 Season Calendar</h2>
我疯狂地尝试按照所有提到的方法自己设置它,但没有运气。就我而言,我使用 css-loader 来创建 css 模块语法,并使用 SSR 来创建不太大的 React 模块。
正如有人提到的那样,因为 webpack 将运行两次,您将以不同的类名结尾,这将在控制台上弹出一些错误,说您的服务器和客户端标记不同。为了缓解这种情况,您可以创建自己的加载程序。
这个想法是存储来自其中一个 webpack 编译的 css-loader 输出的值,并将其用于下一个编译。它可能不适合加载器的设计目的,但它可以完成工作。
/**
* @typedef {Object} LoaderOptions
* @property {"client" | "server"} type
*/
const mapContent = new Map();
/**
* @param {LoaderOptions} options
* @returns boolean
*/
const optionsValidator = (options) => {
return (
typeof options === 'object' &&
'type' in options &&
typeof options.type === 'string' &&
(options.type === 'client' || options.type === 'server')
);
};
module.exports = function (source) {
/**
@type import('./node_modules/webpack/types').LoaderContext<LoaderOptions>
*/
const loader = this;
const options = loader.getOptions();
const logger = loader.getLogger();
if (!optionsValidator(options)) {
logger.error('css-ssr-replacer-loader. Only valid props are "type" with values of "client" or "server"');
}
const isClient = options.type === 'client';
if (isClient) {
mapContent.set(loader.resourcePath, Buffer.from(source));
}
return isClient ? source : mapContent.get(loader.resourcePath);
};
然后在您的 webpack 上,您需要添加如下所示的内容
const webpackConfig = {
module: {
rules: [
{
test: /.css$/,
use: [
{
loader: 'howEverYouWantToCallTheLoader',
options: {
type: 'client' || 'server'
}
},
{
loader: 'css-loader',
options: {
modules: {
exportLocalsConvention: 'camelCase',
localIdentName: '[local]_[hash:base64:8]',
mode: 'local'
}
}
}
]
}
]
},
resolveLoader: {
alias: {
howEverYouWantToCallTheLoader: path.resolve(__dirname, 'pathToYourLoader.js')
}
}
};