使用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啟動項目