2

我正在尝试使用 SSR 将 CSS 添加到我在 React 中构建的组件中,但我无法这样做。

我看过的东西:

但没有一个过程是简单的或明确提到的。我尝试了很多是同构加载器,它看起来很有希望,但是在我的 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,
};
4

1 回答 1

5

下面的配置使 CSS 工作
安装包:
babel-plugin-dynamic-import-node, babel-plugin-css-modules-transform, mini-css-extract-plugin, css-loader, style-loader

index.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>
于 2019-07-14T06:51:44.113 回答