搭建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,
          },
        },
      },
    },
  ],
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章