两者使用为了修改webpack配置,无需eject
npm i customize reacta-app-rewired -D
/*
* 基于customize 和 react-app-rewired的定制化配置文件
* */
// 引入相关的方法
const {
override,
addLessLoader
} = require('customize-cra')
module.export = override(
addLessLoader({
javascriptEnabled: true
})
)
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
},
使用 babel-plugin-import#
注意:antd 默认支持基于 ES module 的 tree shaking,js 代码部分不使用这个插件也会有按需加载的效果。
babel-plugin-import 是一个用于按需加载组件代码和样式的 babel 插件(原理),现在我们尝试安装它并修改 config-overrides.js 文件(与package.json同级)。
npm i babel-plugin-import -D
// 引入相关的方法
const {
override,
addLessLoader,/*引入less方法*/
fixBabelImports/*按需加载antd*/
} = require('customize-cra')
module.exports = override(
//注意调用顺序!!!!!!!!!!!不然样式不起作用
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: true,
}),
//引入less
addLessLoader({
javascriptEnabled: true,
modifyVars: { '@primary-color': '#1DA57A' },//自定义主题
})
)
// 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;
1.定义一个高阶组件Hoc.jsx(如版权信息功能)
import React, {Component} from "react";
const withCopyRight = (MyComponent) => {
return class withCopyRight extends Component {
render() {
return (
<>
<MyComponent {...this.props}/>
<div>©sam</div>
</>
)
}
}
}
export default withCopyRight;
2.使用
import React, {Component} from 'react';
import {Button} from 'antd'
import './css/index.less'
import Hoc from './Hoc'
import MyButton from "./MyButton";
@Hoc //装饰器写法
class App extends Component {
render() {
return (
<div className="App">
<MyButton name={'click'}/>
</div>
);
}
}
export default App;
写法等同
//普通写法
class App extends Component {
render() {
return (
<div className="App">
<MyButton name={'click'}/>
<Button type="primary">666</Button>
</div>
);
}
}
export default Hoc(App);