我正在尝试使用CSS模块来设置我的react组件的样式。我在webpack构建中配置了sass-loader,但是样式没有应用到我的组件。请参阅下面的组件示例和我的webpack配置。我在webpack中做错了什么导致此问题,还是在编写组件时做错了什么?谢谢!
sampleComponent.js:
import React from 'react';
import styles from './sampleComponent.scss';
const SampleComponent = (
<p className={styles.description}>This is some text</p>
);
export default SampleComponent;
sampleComponent.scss:
.description {
color: blue;
font-size: 20px;
}
webpack.common.js:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require('webpack');
const DIST_DIR = path.resolve(__dirname, "dist");
const SRC_DIR = path.resolve(__dirname, "src");
const config = {
entry: [
"babel-polyfill",
`${SRC_DIR}/app/index.js`,
`${SRC_DIR}/app/assets/stylesheets/application.scss`,
`${SRC_DIR}/app/components/index.scss`,
"font-awesome/scss/font-awesome.scss",
"react-datepicker/dist/react-datepicker.css",
"rc-time-picker/assets/index.css",
"react-circular-progressbar/dist/styles.css",
"@trendmicro/react-toggle-switch/dist/react-toggle-switch.css",
],
output: {
path: `${DIST_DIR}/app/`,
filename: "bundle.js",
publicPath: "/app/"
},
module: {
rules: [
{
enforce: "pre",
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
failOnWarning: false,
failOnError: true
}
},
{
test: /\.js$/,
include: SRC_DIR,
loader: 'babel-loader',
query: {
presets: ['react', 'stage-2']
}
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader',
]
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: ['file-loader?context=src/images&name=images/[path][name].[ext]', {
loader: 'image-webpack-loader',
query: {
mozjpeg: {
progressive: true,
},
gifsicle: {
interlaced: false,
},
optipng: {
optimizationLevel: 7,
},
pngquant: {
quality: '75-90',
speed: 3,
},
},
}],
exclude: path.resolve(__dirname, "node_modules"),
include: __dirname,
},
{
test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
// loader: "url?limit=10000"
use: "url-loader"
},
{
test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
use: 'file-loader'
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "application.css"
}),
new webpack.DefinePlugin({
'process.env.INTERNAL': JSON.stringify(process.env.INTERNAL),
}),
],
};
module.exports = config;
答案 0 :(得分:1)
您可以做类似的事情
import React from 'react';
import './sampleComponent.scss';
const SampleComponent = (
<p className="description">This is some text</p>
);
export default SampleComponent;