React支持less

本文介绍了如何在Webpack配置中安装并使用less-loader处理Less文件,从添加loader到解决编译错误,包括CSS和LESS模块化支持。遇到问题时,给出了从less-loader 8.0.0回退到5.0.0的解决方案,以及CSS样式设置失效的排查技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、安装less-loader

yarn add less-loader

2、暴露配置信息

yarn ejcet

3、找打config/webpack.config.js

4、添加lessRegex和lessModuleRegex

// 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$/

5、添加less-loader支持

 {
    loader: require.resolve('less-loader'),
    options: lessOptions,
 },

6、将cssRegex的配置复制一份,放在cssRegex后面

{
    test: lessRegex,
    exclude: lessModuleRegex,
    use: getStyleLoaders({
        importLoaders: 1,
        sourceMap: isEnvProduction
            ? shouldUseSourceMap
            : isEnvDevelopment,
    }, '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 (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
    test: lessModuleRegex,
    use: getStyleLoaders({
        importLoaders: 1,
        sourceMap: isEnvProduction
            ? shouldUseSourceMap
            : isEnvDevelopment,
        modules: {
            getLocalIdent: getCSSModuleLocalIdent,
        },
    }, 'less-loader'),
}

7、遇到的问题

(1)编译出错

ValidationError: Invalid options object. Less Loader has been initialized using an options object that does not match the API schema

将less-loader@8.0.0变为less-loader@5.0.0

(2)css、less设置不生效

需要在父类的div节点上设置,在组件上设置不生效。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值