我们在用react脚手架搭建项目的时候,webpack的相关配置已经被隐藏了。如果要解决less样式无效这个问题,那么我们需要先把webpack的相关配置暴露出来。
先贴一下我react和webpack的版本,因为我在查资料的时候发现config最后暴露出来的文件和网上的不一样。
1、安装less依赖
npm install less less-loader
- 1
2、暴露配置:
npm run eject
- 1
3、修改配置文件
经过第二步之后,你的项目会多一个config的文件夹,里面的内容如上图。
然后需改一下webpack.config.js即可。
(1)、在47行左右添加lessRegex 和lessModuleRegex ,参考上面的cssRegex和cssModuleRegex
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && require.resolve('style-loader'),
isEnvProduction && {
loader: MiniCssExtractPlugin.loader,
// css is located in `static/css`, use '../../' to locate index.html folder
// in production `paths.publicUrlOrPath` can be a relative path
options: paths.publicUrlOrPath.startsWith('.')
? { publicPath: '../../' }
: {},
},
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
{
loader: require.resolve('less-loader')
},
图中的最后一个大括号的内容。
(3)、在326行左右你会看到一个module,里面有strictExportPresence,rules等参数。再配置两个关于less的参数即可。参照463行左右的sassRegex和sassModuleRegex。
{
test: lessRegex,
exclude: lessModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction && shouldUseSourceMap,
},
'less-loader'
),
sideEffects: true,
},
{
test: lessModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
},
'less-loader'
),
},
最后重启项目,然后坐等Compiled successfully!的提示就好了。