注: webpack 版本为 4+
使用 create-react-app
创建的项目默认不支持 less语法, 所以要手动配置
暴露配置文件
create-react-app
生成的项目看不到 webpack 相关的配置文件,需要先暴露出来,使用如下命令即可
npm run eject
安装依赖
yarn add less less-loader antd babel-plugin-import
修改配置
1. package.json
"babel": {
"presets": [
"react-app"
],
"plugins": [
[
"import",
{
"libraryName": "antd",
"style": true
}
]
]
}
2. webpack.config.js
/* start */
和 /* end */
之间为添加的代码
- 定义全局变量
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
/* start */
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
/* end */
- 定义全局样式
if (preProcessor) {
loaders.push(
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: isEnvProduction && shouldUseSourceMap
}
},
{
loader: require.resolve(preProcessor),
options: {
sourceMap: true
}
}
);
/* start */
let loader = require.resolve(preProcessor);
if (preProcessor === 'less-loader') {
loader = {
loader,
options: {
modifyVars: {
// 主题
'primary-color': ' #1890ff '
},
javascriptEnabled: true
}
};
}
loaders.push(loader);
/* end */
}
- 配置 less-loader
找到 oneOf
数组, 在里面添加
// Opt-in support for SASS (using .scss or .sass extensions).
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap
},
'sass-loader'
),
// 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, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
getLocalIdent: getCSSModuleLocalIdent
}
},
'sass-loader'
)
},
/* start */
{
test: lessRegex,
exclude: lessModuleRegex,
use: getStyleLoaders({ importLoaders: 2 }, 'less-loader')
},
{
test: lessModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
modules: {
getLocalIdent: getCSSModuleLocalIdent
}
},
'less-loader'
)
},
/* end */
重启项目
警告是不是消失了 : )