首页 > 解决方案 > 使用类和 id 的 Webpack CSS 不起作用

问题描述

我正在尝试将我的反应应用程序从客户端渲染转换为服务器端渲染。如果我在元素上添加 CSS,则 css 正在呈现或工作正常,但我在任何类或 id 上添加 css 它不起作用。项目目录

PROJECTROOT
 - build
 - src
  -- pages
    --- homepage
       ---- homepage.js
       ---- homepage.css
    --- contactus
       ---- contactus.js
       ---- contactus.css
  -- App.js
  -- Client.js
  -- routes.js
 - server.js
 - webpack.client.js
 - webpack.server.js

Webpack.server.js

const path = require('path');
const webpackExternals = require('webpack-node-externals');
module.exports = {
    mode: 'development',
    target: 'node',
    entry: './server.js',
    output:{
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'build'),
        publicPath:'/build'
    },
    module:{
        rules:[
            {
                test:/\.js$/,
                loader:'babel-loader',
                exclude:'/node_modules/',
                options:{
                    presets:[
                        '@babel/react',
                        ['@babel/env',{
                            targets:{browsers:['last 2 version']}
                        }]
                    ]
                }
            },
            {
                test: /\.css$/,
                loader: 'ignore-loader'
            },
            { test: /(\.woff|\.woff2)$/, loader: 'url?name=font/[name].[ext]&limit=10240&mimetype=application/font-woff' },
            { test: /\.ttf$/, loader: 'ignore-loader' },
            { test: /\.eot$/, loader: 'ignore-loader' }
        ]
    },
    externals:[webpackExternals()]
}

webpack.client.js

const path = require('path');
const webpackExternals = require('webpack-node-externals');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
    mode: 'development',
    target: 'node',
    entry: './src/client.js',
    output:{
        filename: 'client_bundle.js',
        path: path.resolve(__dirname, 'build/public'),
        publicPath:'/build/public'
    },
    module:{
        rules:[
            {
                test: /\.svg$/,
                use: 'file-loader'
            },
            {
                test:/\.js$/,
                loader:'babel-loader',
                exclude:'/node_modules/',
                options:{
                    presets:[
                        '@babel/react',
                        ['@babel/env',{
                            targets:{browsers:['last 2 version']}
                        }]
                    ]
                }
            },
            {
                test: /\.css$/,
                exclude: /node_modules/,
                //use: [ 'style-loader', 'css-loader' ]
                use: [
                    'style-loader',
                    {
                        loader: 'css-loader',
                        options: {
                            modules: true,
                        },
                    },
                ],
            }
        ]
    }
}

服务器.js

import 'babel-polyfill';
import express from "express";
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import App from "./src/App";
import {matchPath,StaticRouter} from 'react-router-dom';
import routes from "./src/routes";
import bodyParser from "body-parser";

const PORT = process.env.PORT||3000;
const app = express();

app.use(bodyParser.json());
app.use(express.static('build/public'));

app.get('*',(req,res,next)=>{
    const activeRoute = routes.find((route)=>matchPath(req.url,route)||{})
    const promise = activeRoute.fetchInitialData?activeRoute.fetchInitialData(req.path):Promise.resolve()
    promise.then((data)=>{
        const context = {};
    console.log("Requesting on url ",req.url);
    const reactContent = ReactDOMServer.renderToString(
        <StaticRouter location={req.url} context={context}>
            <App/>
        </StaticRouter>
        );

        const html = `
            <html>
                <head>
                </head>
                <body>
                    <div id="root">${reactContent}</div>
                    <script src='client_bundle.js'defer></script>
                </body>
            </html>
        `;
        res.send(html);
    }).catch(next);
    
    
});
app.listen(PORT,()=>{
    console.log(`Server is running on ${PORT}`);
});

路由.js

import HomePage from "./pages/homepage/homepage";
import ContactUsPage from "./pages/contactus/contactuspage";

const routes = [
    {
        path:'/',
        exact:true,
        component:HomePage
    },
    {
        path:'/contactus',
        exact:true,
        component:ContactUsPage
    }
]

export default routes;

客户端.js

import React from "react";
import ReactDOM from "react-dom";
import {BrowserRouter} from 'react-router-dom';
import App from "./App";

ReactDOM.hydrate(
    <BrowserRouter>
        <App/>
    </BrowserRouter>,document.querySelector("#root"));

应用程序.js

import React, {Component} from 'react';
import routes from "./routes";
import {Route,Switch} from 'react-router-dom';
class App extends Component {
    render(){
        return(
            <div>
                <Switch>
                    {routes.map(({path, exact, component: C, ...rest})=>(
                        <Route key={path}
                        path={path}
                        exact={exact}
                        render={(props)=>(
                            <C {...props} {...rest} />
                            )}
                        />
                    ))}
                </Switch>
            </div>
        )
    }
}

export default App;

主页.js

import React, {Component} from 'react';
import "./homepage.css";
class HomePage extends Component {
    buttonClick(e){
        console.log("Clicked on button");
    }
    componentDidMount(){
        console.log("Component did mount");
    }
    render(){
        return(
            <div className="hello">Hello its home page
                <br></br>
                <button onClick={this.buttonClick}>Click on this button</button>
            </div>
        )
    }
}

export default HomePage;

主页.css

//Not Working
.hello{
    color: red;
}
//Working
button {
   color:red;
}

为什么 CSS 在应用于 class OR ID 时不起作用?

标签: cssreactjswebpackwebpack-style-loader

解决方案


推荐阅读