一、create-react-app 脚手架搭建的react项目不支持 less,配置less步骤:
1、使用命令将配置文件暴露出来
yarn eject // 或者 npm run eject
注意:yarn eject或者npm run eject 报错This git repository has untracked files or uncommitted changes,因为我们没有没有进行git提交,解决方案:将代码提交到git仓库.
2、安装 less,less-loader 插件
yarn add less less-loader // 或者 npm install less less-loader --save
3、打开 项目中的config 文件夹,修改 webpack.config.js,找到style files regexes ,添加两行代码,见下
// 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$/;
// 上面俩行代码为新添加
4、 在webpack.config.js文件中搜索"getStyleLoaders",找到后,修改 getStyleLoaders 函数,见下面代码
// common function to get style loaders
// 把lessOptions加到形参里面
const getStyleLoaders = (cssOptions, lessOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && require.resolve('style-loader'),
isEnvProduction && {
loader: MiniCssExtractPlugin.loader,
options: shouldUseRelativeAssetPaths ? { publicPath: '../../' } : {},
},
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
// 下面为新加的代码
{
loader: require.resolve('less-loader'),
options: lessOptions,
},
// 上面为新加的代码
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
5、 在webpack.config.js文件中搜索"cssRegex",找到后,在 css 配置下添加 less 配置(lessRegex,lessModuleRegex),见下面代码
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
}),
},
{
test: lessRegex,
exclude: lessModuleRegex,
use: getStyleLoaders(
{
importLoaders: 1,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
},
'less-loader'
),
sideEffects: true,
},
{
test: lessModuleRegex,
use: getStyleLoaders(
{
importLoaders: 1,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
},
'less-loader'
),
},
6、重新启动项目,less 配置就成功了。
二、按需加载配置
在package.json中添加以下代码(这里拿antd举例)
"babel": {
"presets": [
"react-app"
],
"plugins": [
[
"import",
{
"libraryName": "antd",
"style": "css"
}
]
]
}