您当前的位置: 首页 > 

【03】

暂无认证

  • 3浏览

    0关注

    196博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

react实现局部样式、全局样式、antd-mobal按需共存

【03】 发布时间:2020-08-22 19:26:48 ,浏览量:3

前言

众所周知,react的css在默认情况下无论在哪个组件引用,都是全局的,后 覆盖 前(对于权重高的不覆盖,相当于css的书写顺序)

准备

react暴露配置文件

react配置less-loader

配置antd-mobal按需引入

在上面基础之上,解决以下问题 1、实现全局css以及局部css 2、局部css适配antd-mobal的按需引入

webpack.config.js 把之前配置less产生的部分代码恢复为

const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;

{
  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/6571
  sideEffects: true,
},
{
  test: cssModuleRegex,
  use: getStyleLoaders({
    importLoaders: 1,
    sourceMap: isEnvProduction && shouldUseSourceMap,
    modules: {
      getLocalIdent: getCSSModuleLocalIdent,
    },
  }),
},

添加以下代码

const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
{
  test: lessRegex,
  exclude: lessModuleRegex,
  use: getStyleLoaders(
    {
      importLoaders: 3,
      sourceMap: isEnvProduction && shouldUseSourceMap,
    },
    'less-loader'
  ),
  sideEffects: true,
},
// Adds support for CSS Modules, but using LESS
// using the extension .module.scss or .module.less
{
  test: lessModuleRegex,
  use: getStyleLoaders(
    {
      importLoaders: 3,
      sourceMap: isEnvProduction && shouldUseSourceMap,
      modules: {
        getLocalIdent: getCSSModuleLocalIdent,
      },
    },
    'less-loader'
  ),
},

以下为关键代码选区

使用 使用全局css

定义全局.less文件, index.js中

import './styles/global.less';

使用局部css

AntdTest.jsx

import React, {Component} from 'react'
import {withRouter} from "react-router-dom";
import style from './AntdTest.module.less'
class AntdTest extends Component {
  render() {
    return (
      
) } } export default withRouter(AntdTest);
.box{
  background: #0e80d2;
  width: 100px;
  height: 100px;
}

AntdTest.module.less

.box{
  background: #0e80d2;
  width: 100px;
  height: 100px;
}

注意:命名局部css的时候,一定要加上modal.less,如xxx.modal.less,否则不匹配生效

关注
打赏
1657344724
查看更多评论
立即登录/注册

微信扫码登录

0.0447s