1.npx create-react-app my-app
需要node版本>14.x
2.按需加载:npm add react-app-rewired customize-cra babel-plugin-import
3.定义加载配置的js模块:config-overrides.js
module.exports = override(
fixBabelImports("import", {
//配置引用babel-plugin-import
libraryName: "antd", //针对antd进行打包
libraryDirectory: "es", //源码文件夹中的es文件夹
style: "css", //自动打包相关的css
})
);
4.修改package.json
"scripts": {
"start": "react-app-rewried start",
"build": "react-app-rewried build",
"test": "react-app-rewried test"
},
"dependencies": {
"react-app-rewired": "^2.1.11",//新增配置命令的包
"react-scripts": "5.0.0",//原来的
},
5.使用antd
npm install antd
import React from "react";
import { Button, message } from "antd";
class App extends React.Component {
handleClick = () => {
message.success("成功饿了");
};
render() {
return (
<Button type="primary" onClick={this.handleClick}>
学习
</Button>
);
}
}
export default App;
6.自定义主题色,配置less。config-overrides.js
addLessLoader({
lessOptions: {
javascriptEnabled: true,
ModifyVars: { "@primary-color": "#eee" },
},
});
7.测试:App.js。成功后可以看到按钮设置type="primary"按钮颜色显示为绿色了。
import React, { Component } from "react";
import { Button, message } from "antd";
import { render } from "react-dom";
class App extends Component {
handleClick = () => {
message.success("成功饿了");
};
render() {
return (
<div className="App">
<Button
type="primary"
onClick={() => {
this.handleClick();
}}
>
学习
</Button>
</div>
);
}
}
export default App;
index.js
/*
入口js
*/
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("root"));
报错:
webpack新的版本里面配置less,使用LessOptions配置
降低less-loader版本为5.0.0->报如下错误:
已经降低了less-loader版本还是报错,重新删掉之前的Npm包,重新Install
最终package.json文件:
"dependencies": {
"@testing-library/jest-dom": "^5.16.1",
"@testing-library/react": "^12.1.2",
"@testing-library/user-event": "^13.5.0",
"antd": "^3.17.0",
"babel-plugin-import": "^1.11.0",
"customize-cra": "^0.2.12",
"less": "^3.9.0",
"less-loader": "^5.0.0",
"react": "^16.8.6",
"react-app-rewired": "^2.1.3",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1"
},
补充:因为版本的问题,我们每次npm install的都是最新版本,因此有些引入的包会不兼容,需要我们点进相应包的package.json文件里面查看对应的版本,然后进行install。