最新版react16.9中按需加载antd和使用less
2024-09-01 18:51:31
使用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对默认设置自定义
最新文章
- Java继承和接口
- Linux下的split 命令(将一个大文件根据行数平均分成若干个小文件)
- .NET 进程和线程
- 拿起cl.exe,放下IDE
- java中IO写文件工具类
- General Thread States
- 原创:Docker在云家政的应用 谢绝复制粘贴内容
- JS排序
- OpenCv结构和内容
- 模拟vue的tag属性,在react里实现自定义Link
- .net 多线程临时变量
- 如何命名Java变量
- c语言程序设计 第一例子
- 利用matplotlib的plot函数实现图像绘制
- 如何在Win10上永久禁用Windows Defender Antivirus
- 【技术课堂】如何管理MongoDB数据库?
- VS2013代码调试:[7]如何避免调试时加载符号
- koa2 知识点
- bzoj 1468 Tree 点分
- 2017年11月3日 VS三大类&;数组&;VS的冒泡排序&;集合&;泛型集合