在react项目中使用less
- 安装依赖包:cnpm i --save-dev less less-loader (less 、less-loader两个包)
- npm run eject 来暴露webpack的配置文件,你会发现多了config为名的文件夹。如果这步报错没关系,其实我们只需要在之前运行 git add . 命令,然后再运行 git commit -m “init” 命令就可以解决。
- 修改webpack配置
代码:
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
代码:
{
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/6571
sideEffects: 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'
),
},
- 然后就可以正常使用了
参考:http://www.pianshen.com/article/3668378466/