A17 React+AntDesign AntDesignUI框架 css樣式按需引入


官方文檔參考

Antd中使用高級配置,按需引入css樣式

步驟:

Ⅰ、$ yarn add react-app-rewired customize-cra / $ 1、cnpm install react-app-rewired --save  2、$ cnpm install customize-cra --save 

  引入 react-app-rewired 並修改 package.json 里的啟動配置。由於新的 react-app-rewired@2.x 版本的關系,你還需要安裝 customize-cra

  $ yarn add react-app-rewired customize-cra
  /* package.json */   "scripts": {   - "start": "react-scripts start",   + "start": "react-app-rewired start",   - "build": "react-scripts build",   + "build": "react-app-rewired build",   - "test": "react-scripts test",   + "test": "react-app-rewired test",   }

Ⅱ、然后在項目根目錄創建一個 config-overrides.js 用於修改默認配置。

  module.exports = function override(config, env) {     // do stuff with the webpack config...      return config;     };

Ⅲ、使用 babel-plugin-import

注意:antd 默認支持基於 ES module 的 tree shaking,js 代碼部分不使用這個插件也會有按需加載的效果。

babel-plugin-import 是一個用於按需加載組件代碼和樣式的 babel 插件(原理),現在我們嘗試安裝它並修改 config-overrides.js 文件。

$ yarn add babel-plugin-import / cnpm install babel-plugin-import --save
  + const { override, fixBabelImports } = require('customize-cra');   - module.exports = function override(config, env) {   - // do stuff with the webpack config...   - return config;   - };   + module.exports = override(   + fixBabelImports('import', {   + libraryName: 'antd',   + libraryDirectory: 'es',   + style: 'css',   + }),   + );

Ⅳ、然后移除前面在 src/App.css 里全量添加的 @import '~antd/dist/antd.css'; 樣式代碼,並且按下面的格式引入模塊。

 // src/App.js import React, { Component } from 'react'; - import Button from 'antd/es/button'; + import { Button } from 'antd'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <Button type="primary">Button</Button> </div> ); } } export default App;

Ⅴ、最后重啟 yarn start 訪問頁面,antd 組件的 js 和 css 代碼都會按需加載

 

====================================================================================

至此 A系列入門學習完結

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM