我尝试通过使用 Webpack 的 css 加载器插件分别为每个组件设置样式。但是当文件具有相同的名称(例如:"index.scss")并且具有相同的属性(例如:".container")时,它将结合两种样式,但在这种情况下,我只需要一个。我该如何解决
这是我的 Webpack 配置:
rules: [
{
test: /.(sa|sc|c)ss$/,
use: [
{
loader: 'style-loader',
options: {
insertAt: 'top',
sourceMap: true
}
},
{
// Handle import/ require css
// It help to css for each component
// https://github.com/webpack-contrib/css-loader#scope
loader: 'css-loader',
options: {
sourceMap: true ,
localIdentName: '[path][name]__[local]--[hash:base64:5]',
camelCase: true,
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: true,
// minimize: true,
plugins: () => [
require('postcss-flexbugs-fixes'),
// Help to generate specific css for each component
// require('postcss-modules'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
}
},
{ loader: 'sass-loader', options: { sourceMap: true } },
],
},
]
例: src/screen1/index.tsx
const styles = require('./index.scss')
const Dashboard = ({ children, url }: IDashboardPropsIn) => {
return (
<div className={styles.body}>
{children}
</div>
)
}
我有 2 个文件:src/screen2/index.scss
和 src/screen1/index.scss
不知何故,在类中哪个名称body--[hash:64]
具有 2 个文件中的两种样式
src/screen1/index.scss
:local {
.body {
grid-area: body;
background-color: $white;
}
}
和src/screen2/index.scss
:local {
.body {
display: flex;
}
}
body--[hash:64]
风格将是
grid-area: body;
background-color: $white;
display: flex;
但在这种情况下,我只有一个导入文件src/screen1/index.scss
例如
grid-area: body;
background-color: $white;
我该如何解决这个问题?
您没有在配置中指定modules
选项
{
// Handle import/ require css
// It help to css for each component
// https://github.com/webpack-contrib/css-loader#scope
loader: 'css-loader',
options: {
sourceMap: true ,
localIdentName: '[path][name]__[local]--[hash:base64:5]',
camelCase: true,
modules: true, // or 'local' | 'global' | false
}
},
在文档中阅读更多内容
css-loader
软件包更新到 0.28.11 版本