我有一个 React 应用程序,我想要 sass 和 css 支持。问题是当我导入 sass 或 css 模块时,它不会应用于标签。我的意思是看看下面的代码,我想要使用样式的第二种方式:
import React from 'react';
import PropTypes from 'prop-types';
import style from './index.module.scss';
import { Header, Footer, Container } from '..';
import './style.scss'; // 1. this way is applying
import style from './style.scss'; // 2. this way is not applying
export const Layout = ({ children }) => (
<div className="content"> // 1. this way is applying
<Header />
<Container>
<div className={style.content}> // 2. this way is not applying
{children}
</div>
</Container>
<Footer />
</div>
);
Layout.propTypes = {
children: PropTypes.any.isRequired,
};
export default Layout;
这是我的网页包:
const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const cones = require('./cones.json');
module.exports = {
mode: 'development',
entry: './src/index',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build'),
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new CopyWebpackPlugin([{ from: 'public/index.html' }]),
],
devServer: {
port: 3000,
contentBase: path.join(__dirname, './public'),
hot: true,
open: true,
historyApiFallback: true,
before(app) {
app.get('/api/cones', (req, res) => {
res.json(cones);
});
},
},
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.js', '.jsx', '.scss'],
},
};
我认为style-loader有问题,无法以这种方式加载样式模块。
“第二种方式”称为 CSS 模块。为了使用它,您需要在
modules
选项中打开 css-loader
。看看这是否有效:
{
test: /\.s[ac]ss$/i,
loader: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
},
},
'sass-loader',
],
},
如果
import * as styles from "SomeStyles.scss"
工作正常且 import styles from "SomeStyles.scss"
未尝试将 options.modules.namedExport: false
应用于 css-loader
:
{
test: /\.s[ac]ss$/i,
use: [
'style-loader',
{
loader: `css-loader`,
options: {
modules: {
namedExport: false
}
}
},
'sass-loader',
],
}
请注意,如果您使用 Typescript
"esModuleInterop": true
标志应启用。