LESS是一个CSS预处理器,比如antD就是基于LESS的。
要在react中使用LESS,需要暴露webpack配置并进行修改,同时安装less和less-loader。
当然网上可以找到很多教程,关于如何修改的,但貌似webpack现在的最新版本,配置文件和以前不一样了,以前的教程照着做会很头大,我也是刚琢磨出来,把解决方法分享一下,当然,你看到的时候可能又过期了,不过值得一试。
首先,你需要安装LESS和LESS-LOADER:
yarn add less-loader less
然后暴露webpack配置:
yarn eject
在暴露出的配置中找到config\webpack.config.js
并编辑。(这里就和我看的教程里不一样了,教程中是有webpack.config.dev.js和webpack.config.prod.js两个文件)
- 找到:
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
复制并粘贴,然后修改为:
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
2. 找到:
{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/6571sideEffects: 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,}),sideEffects: true,},{test: lessModuleRegex,use: getStyleLoaders({importLoaders: 1,sourceMap: isEnvProduction && shouldUseSourceMap,modules: true,getLocalIdent: getCSSModuleLocalIdent,}),},
3. 找到:
loader: require.resolve('postcss-loader'),
在其末尾后面添加:
{loader: require.resolve('less-loader')},
最后,重新yarn start项目,less文件就可以被读取了。