【发布时间】:2018-04-05 13:22:40
【问题描述】:
我正在学习 react,我配置了 webpack,而不是使用 webpack 4 的 create-react-app。我已将样式应用于组件,但样式不会影响组件,但会影响我在 css 文件中设置的背景颜色正在影响页面。可能是什么问题呢?没有显示错误消息。请参阅下面的 webpack.config.js 文件和组件的代码
Webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const port = process.env.PORT || 3000;
const paths = {
DIST: path.resolve(__dirname, 'dist'),
SRC: path.resolve(__dirname, 'src'),
};
const htmlPlugin = new HtmlWebpackPlugin({
template: "./src/index.html",
filename: "./index.html"
});
module.exports = {
mode: 'development',
entry: path.join(paths.SRC, 'index.js'),
output: {
path: paths.DIST,
filename: 'app.bundle.js'
},
module:{
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [
{
loader: "style-loader"
},
{
loader: "css-loader",
options:{
modules: true,
importLoaders: 1,
localIndentName: "[name]_[local]_[hash:base64]",
sourceMap: true,
minimize: true,
camelCase:true
}
}
]
}
]
},
plugins: [
htmlPlugin,
new webpack.HotModuleReplacementPlugin()
],
devServer: {
// contentBase: paths.JS,
// publicPath: paths.DIST,
host: 'localhost',
port: port,
historyApiFallback: true,
open:true,
//hot: true,
inline: true
}
};
App.js
import React, {Component} from 'react';
import './index.css';
class App extends Component{
render(){
const helloWorld = 'Welcome to the Road to learn React';
return (
<div className="app">
<h2>{helloWorld}</h2>
</div>
);
}
}
export default App;
【问题讨论】:
-
你是如何设置样式的?
-
你是如何设置样式的?在 react 样式属性中,接受带有驼峰式属性的 javascript 对象,而不是我们在 css 类中提供的普通属性。所以你应该给出类似 style={{ backgroundColor: 'red'}}
-
如果您尝试使用 CSS 模块,我相信您需要使用名称
import styles from './index.css'导入样式表,然后从导入的对象中引用 css 类名称。className="{styles.app}". -
如果你看上面的代码,有一行导入了css。当您使用 create-react-app 时,它会以这种方式工作。它不适用于我使用 webpack 设置的那个。
-
@Kyle Lussier 你是对的,但是,className 应该是这样的:className={styles.app} 没有引号
标签: javascript css reactjs webpack