最新版react16.9中按需加載antd和使用less


使用create-react-app創建應用

yarn create react-app my-app

cd my-app

yarn start

引入 antd

這是 create-react-app 生成的默認目錄結構。

├── README.md
├── package.json
├── public
│   ├── favicon.ico
│   └── index.html
├── src
│   ├── App.css
│   ├── App.js
│   ├── App.test.js
│   ├── index.css
│   ├── index.js
│   └── logo.svg
└── yarn.lock

現在從 yarn 或 npm 安裝並引入 antd。

yarn add antd

按需加載

引入react-app-rewired ,這是一個可以自定義react項目配置的庫, 對於使用Webpack 4的create-react-app 2.x:

yarn add react-app-rewired --dev

由於新的 react-app-rewired@2.x 版本的關系,需要安裝 customize-cra

yarn add customize-cra --dev

修改package.json項目啟動項

/* package.json */

// 舊的
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

// 替換
"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test"
},

安裝babel-plugin-import插件

babel-plugin-import 是一個用於按需加載組件代碼和樣式的 babel 插件(原理),在項目根目錄創建一個 config-overrides.js 用於修改默認配置。添加以下內容:


const { override, fixBabelImports } = require('customize-cra');

module.exports = override(
    fixBabelImports('import', {
        libraryName: 'antd',
        libraryDirectory: 'es',
        style: 'css',
    }),
);

使用less

yarn add less less-loader --dev

修改config-overrides.js文件,添加以下內容:

-  const { override, fixBabelImports } = require('customize-cra');
+ const { override, fixBabelImports,addLessLoader } = require('customize-cra');

module.exports = override(
    fixBabelImports('import', {
        libraryName: 'antd',
        libraryDirectory: 'es',
        style: 'css',
    }),
 + addLessLoader({        
 +     javascriptEnabled: true,        
 +     modifyVars: { 
 +       '@primary-color': '#1DA57A' 
 +     }    
 +  })
);

使用scss

scss無需配置,安裝插件即可使用

yarn add node-sass sass-loader --dev

修改 src/App.js,引入 antd 的按鈕組件。

import React, { Component } from 'react';
import Button from 'antd/es/button';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <Button type="primary">Button</Button>
      </div>
    );
  }
}

export default App;

修改src/App.css為 App.less

.App {
  text-align: center;
}
.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
  .App-logo {
  animation: App-logo-spin infinite 20s linear;
  height: 40vmin;
  pointer-events: none;
  }
  .App-link {
  color: #61dafb;
  }
}

最后 yarn start啟動項目

參考資料: 使用react-app-rewired和customize-cra對默認設置自定義


免責聲明!

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



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