• 搭建react项目,react+antd按需加载和less配置


    全局安装create-react-app

    npm install -g create-react-app

    创建项目

    yarn create react-app react-antd-demo

    安装antd包

    yarn add antd

    由于antd使用了less,所以如果想配置主题的话,我们也需要安装less,这里我们使用antd官网推荐的craco,然后修改package.josn文件

    yarn add @craco/craco craco-less
    "scripts": {
    -   "start": "react-scripts start",
    -   "build": "react-scripts build",
    -   "test": "react-scripts test",
    +   "start": "craco start",
    +   "build": "craco build",
    +   "test": "craco test",
    }

    在项目根目录新建craco.config.js

    const CracoLessPlugin = require('craco-less');
    module.exports = {
      plugins: [
        {
          plugin: CracoLessPlugin,
          options: {
            lessLoaderOptions: {
              lessOptions: {
                modifyVars: { '@primary-color': '#1DA57A' },//主题颜色
                javascriptEnabled: true,
              },
            },
          },
        },
      ],
    }

    配置完成以上步骤,项目里就可以使用less开发了

    实际项目中,为了缩小打包后的体积,往往需要用到按需加载,步骤如下:

    1.安装babel-plugin-import

    yarn add babel-plugin-import

    然后在craco.config.js里加上

    babel: {
         plugins: [
            [
                "import", 
                {
                    "libraryName": "antd",
                    "libraryDirectory": "es",
                     "style": true //设置为true即是less
                 }
             ]
         ]
    },

    以上配置完成后,在引用组件时,无需在额外引入样式文件,babel会自动按需帮你完成样式的引入

    有时候我们还想配置打包文件分析,这时候需要安装webpack-bundle-analyzer,但create-react-app默认没有暴露配置文件,我们往往需要yarn eject 命令,暴露出配置文件,但由于我们上面安装了craco,所以在craco.config.js内配置也是可以的。

    
    
    const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
    webpack: {
            plugins: [
                new BundleAnalyzerPlugin(),
            ]
        },

    完整craco.config.js配置如下

    const CracoLessPlugin = require('craco-less');
    // const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer")
    module.exports = {
      webpack: {
        plugins: [
          // new BundleAnalyzerPlugin(),
        ]
      },
      babel: {
        plugins: [
          [
            "import", 
            {
              "libraryName": "antd",
              "libraryDirectory": "es",
              "style": true// true 针对less
            }
          ]
        ]
      },
      plugins: [
        {
          plugin: CracoLessPlugin,
          options: {
            lessLoaderOptions: {
              lessOptions: {
                modifyVars: { '@primary-color': '#FA8C16' },
                javascriptEnabled: true,
              },
            },
          },
        },
      ],
    };
  • 相关阅读:
    【毒链剖分】
    线段树——从入门到入土
    二分图最大匹配——找老婆问题(确信)
    【AC自动机(有了这个我就能AC了吗)】
    社交距离II
    【扩展KMP(Z函数)(这个区间看着不是很爽)】
    【KMP算法(烤馍片,真香)】
    【最短路系列问题】
    最近公共祖先LCA(我肯定是你的LCA)
    【并查集(又在乱牵线了)】
  • 原文地址:https://www.cnblogs.com/zhangrenjie/p/14297215.html
Copyright © 2020-2023  润新知