我使用create-react-app(使用React版本16.6.3)创建了一个新的React应用。现在,我想对组件使用SCSS。所以首先我运行了弹出脚本。然后在webpack.config.dev.js中,我进行了以下编辑:
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
modules: true,
localIdentName: '[name]__[local]__[hash:base64:5]'
}),
}
我还安装了node-sass软件包。
然后我创建了我的Test .scss文件:
.Test {
background-color: gold;
.Header {
color: lighten(purple, 20%);
}
}
还有我的Test组件,用于导入.scss文件
import React from 'react';
import style from './test.scss';
const Test = (props) => (
<div className={style.Test}>
This is div1
<div className={style.Header}>Div 2</div>
</div>
);
export default Test;
那没有用,我没看到任何样式。我试图直接导入.scss并使用它:
import './test.scss';
...
<div className='Test'>
This is div1
<div className={style.Header}>Div 2</div>
</div>
...
那确实可行,我看到了className ='Test'的div样式。
我尝试如下更改webpack:
const CSSModuleLoader = {
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
localIdentName: '[local]__[hash:base64:5]',
minimize: true
}
}
const CSSLoader = {
loader: 'css-loader',
options: {
modules: false,
sourceMap: true,
minimize: true
}
}
const postCSSLoader = {
loader: 'postcss-loader',
options: {
ident: 'postcss',
sourceMap: true,
plugins: () => [
autoprefixer({
browsers: ['>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9']
})
]
}
}
...
{
test: /\.scss$/,
exclude: /\.module\.scss$/,
use: ['style-loader', CSSLoader, postCSSLoader, 'sass-loader']
},
{
test: /\.module\.scss$/,
use: [
'style-loader',
CSSModuleLoader,
postCSSLoader,
'sass-loader',
]
},
起初,我遇到了autoprefixer not defined
错误。我使用const autoprefixer = require('style-loader')
导入了该文件-尽管我仍然不认为这是正确的要求和正确的解决方法,但该错误消失了。
但是随后出现以下错误:
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.module.rules[2].oneOf[0].use should be one of these:
non-empty string | function | object { loader?, options?, ident?, query? } | function | [non-empty string | function | object { loader?, options?, ident?, query? }]
-> Modifiers applied to the module when rule is matched
Details:
* configuration.module.rules[2].oneOf[0].use should be a string.
* configuration.module.rules[2].oneOf[0].use should be an instance of function
* configuration.module.rules[2].oneOf[0].use should be an object.
* configuration.module.rules[2].oneOf[0].use should be an instance of function
* configuration.module.rules[2].oneOf[0].use[1] should be a string.
* configuration.module.rules[2].oneOf[0].use[1] should be an instance of function
* configuration.module.rules[2].oneOf[0].use[1] has an unknown property 'loaders'. These properties are valid:
object { loader?, options?, ident?, query? }
不知道该如何处理...
如何配置webpack以便立即将.scss编译为同一目录中的.css(这样,我就可以导入.css并定期与style.Class
一起使用)或在文件中使用.scss导入以同样的方式,然后将其编译为.css以进行生产?
答案 0 :(得分:0)
请在webpack文件中使用以下规则,并删除多余的代码。
rules: [
{
test: /\.s?css$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
}
]