react 配置less 及相关报错解决
1、安装less 依赖
npm install less
npm add [email protected](注意安装的版本不宜过高,否则会报错)
/*
ValidationError: Invalid options object. Less Loader has been initialized using an options object that does not match the API schema.
options has an unknown property ‘source’. These properties are valid:
object { lessOptions?, prependData?, appendData?, sourceMap? }
*/
2、暴露配置文件
npm run eject //暴露配置文件 config
//如果报错0.1.0 eject: `react-scripts eject`;
问题原因:脚手架工具为您的项目添加了.gitgnore文件,但是却没有本地仓库。
解决方法:
#cd 你的项目目录
#git init
#git add .
#git commit -m "saving before ejecting"
#npm run eject
然后再执行npm run eject
3、修改webpack.config.js配置文件,共三处
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
## 添加less配置 1
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
// common function to get style loaders
##添加lessOptions 2
const getStyleLoaders = (cssOptions, lessOptions, 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,
},
## 添加less-loader 配置 2
{
loader: require.resolve('less-loader'),
options: lessOptions,
},
## 添加less配置3
{
test: lessRegex,
exclude: lessModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
},
'less-loader'
),
sideEffects: true,
},
{
test: lessModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
},
'less-loader'
),
},