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進(jìn)行打包
libraryDirectory: "es", //源碼文件夾中的es文件夾
style: "css", //自動打包相關(guān)的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}>
學(xué)習(xí)
</Button>
);
}
}
export default App;
6.自定義主題色,配置less嫩痰。config-overrides.js
addLessLoader({
lessOptions: {
javascriptEnabled: true,
ModifyVars: { "@primary-color": "#eee" },
},
});
7.測試:App.js铡溪。成功后可以看到按鈕設(shè)置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();
}}
>
學(xué)習(xí)
</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"));
報(bào)錯:
webpack新的版本里面配置less,使用LessOptions配置
降低less-loader版本為5.0.0->報(bào)如下錯誤:
已經(jīng)降低了less-loader版本還是報(bào)錯肋乍,重新刪掉之前的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"
},
補(bǔ)充:因?yàn)榘姹镜膯栴}甘萧,我們每次npm install的都是最新版本,因此有些引入的包會不兼容财松,需要我們點(diǎn)進(jìn)相應(yīng)包的package.json文件里面查看對應(yīng)的版本瘪贱,然后進(jìn)行install。