我在使用 Node.js 和 Express.js 设置 React 应用程序时遇到 CSS 加载问题。这是我的代码:
Webapck:
const path = require('path');
const nodeExternals = require('webpack-node-externals');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
target: 'node',
mode: 'production',
externals: [nodeExternals()],
entry: './server/index.js',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'build'),
},
plugins: [
// new MiniCssExtractPlugin(),
],
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: 'style-loader',
options: {
insert: 'head', // insert style tag inside of <head>
injectType: 'singletonStyleTag' // this is for wrap all your style in just one style tag
},
},
"css-loader",
],
sideEffects: true,
include: __dirname
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env',
'@babel/preset-react',
],
},
},
},
],
},
resolve: {
extensions: ['.js', '.jsx', '.css'],
modules: [
'node_modules'
]
},
};
index.js(服务器代码)
const express = require('express');
const app = express();
const port = 5005;
const path = require('path');
var ReactDomServer = require('react-dom/server');
import Hello from '../ui.src/hello';
var cors = require('cors');
const axios = require('axios');
// import '../ui.src/assets/css/style.css';
app.use(cors())
app.get("/", (req,res) => {
const component = ReactDomServer.renderToString(<Hello />);
res.send(`<html><body class='testclass'>${component}</body></html>`);
})
app.listen(port, () => {
console.log(`Server now listening at http://localhost:${port}`)
})
反应组件
import React, { useEffect, useState } from 'react';
import './assets/css/style.css';
const Hello = () => {
return (
<h1>Hello World this is Test File....</h1>
)
}
export default Hello;
我的所有组件都工作正常,通过 expess js 我也可以渲染 React 组件,但它没有加载 CSS。尝试了所有选项,但没有成功。如果有任何遗漏,请提出建议。
提前谢谢您。
我已经有一段时间没有搞乱 React 了,但是我在 webpack 配置中注意到的一个问题是使用了 style-loader 和 MiniCssExtractPlugin。由于您使用的是 MiniCssExtractPlugin,因此您应该从 CSS 规则中删除 style-loader。
以下是您可以在 webpack 配置中调整的内容:
module: {
rules: [
{
test: /\.css$/i,
use: [
MiniCssExtractPlugin.loader, // Use MiniCssExtractPlugin instead of style-loader
"css-loader",
],
sideEffects: true,
include: __dirname
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env',
'@babel/preset-react',
],
},
},
},
],
},
此外,请确保将 MiniCssExtractPlugin 添加到 webpack 配置中的插件数组中:
plugins: [
new MiniCssExtractPlugin(),
],
这些更改应该正确地将您的 CSS 文件与 webpack 捆绑在一起,并将样式应用到您的 React 组件。如果您需要进一步的帮助,请告诉我!