安装less
npm install less less-loader --save-dev
暴露 webpack 文件
利用 npx create-react-app 搭建的 React 项目,默认隐藏 webpack 配置文件,引入 less 需要修改 webpack 配置文件,因此我们需要执行命令暴露 webpack 配置文件。
请先将刚刚搭建的React项目初始化并提交代码到本地
git init
git add .
git commit -m "init"
执行如下命令即可,但是一旦暴露无法回退
npm run eject
或
yarn eject
执行完毕后,可以发现项目中多了config文件,找到其中的webpack.config.js
添加如下代码
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
再将以下代码放到 oneof 数组中
{test: lessRegex,exclude: lessModuleRegex,use: getStyleLoaders({importLoaders: 2,sourceMap: isEnvProduction && shouldUseSourceMap,},'less-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/6571sideEffects: true,
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{test: lessModuleRegex,use: getStyleLoaders({importLoaders: 2,sourceMap: isEnvProduction && shouldUseSourceMap,modules: true,getLocalIdent: getCSSModuleLocalIdent,},'less-loader'),
},
最后新建一个app.less文件,使用时将其导入即可。