将CSS添加到React SSR组件

时间:2019-07-12 19:07:13

标签: javascript css reactjs react-ssr

我正在尝试使用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,
};

1 个答案:

答案 0 :(得分:2)

以下配置使CSS正常运行
已安装软件包:
babel-plugin-动态导入节点,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的头部内添加了以下代码。

<link rel="stylesheet" type="text/css" href="./styles.css" />

用法

import  "./../App.css";

<h2 className="wrapper">F1 2018 Season Calendar</h2>