【前端】react脚手架 + antd的craco.config.js配置

1,306 阅读2分钟

react脚手架 + antd的craco.config.js配置
拉取脚手架执行以下命令
标题安装antd
修改 src/App.js,引入 antd 的按钮组件
修改 src/App.css,在文件顶部引入 antd/dist/antd.css
高级配置
安装 craco 并修改 package.json 里的 scripts 属性
然后在项目根目录创建一个 craco.config.js 用于修改默认配置
自定义主题
然后安装 craco-less 并修改 craco.config.js 文件如下
支持装饰器语法和配置代理
配置antd的less按需加载(则反打包后,会增大css文件)
配置别名
拉取脚手架执行以下命令
$ npx create-react-app antd-demo   ->       启动 cd antd-demo   ->   yarn start

标题安装antd
yarn add antd

修改 src/App.js,引入 antd 的按钮组件
import React from 'react';
import { Button } from 'antd';
import './App.css';

const App = () => (
<div className="App">
<Button type="primary">Button</Button>
</div>
);

export default App;

修改 src/App.css,在文件顶部引入 antd/dist/antd.css
@import '~antd/dist/antd.css';     //可以在页面看到蓝色按钮组件了
1
高级配置
安装 craco 并修改 package.json 里的 scripts 属性
yarn add @craco/craco
/* package.json */
"scripts": {
-   "start": "react-scripts start",
-   "build": "react-scripts build",
-   "test": "react-scripts test",
+   "start": "craco start",
+   "build": "craco build",
+   "test": "craco test",
}

然后在项目根目录创建一个 craco.config.js 用于修改默认配置
/* craco.config.js */
module.exports = {
// ...
};

自定义主题
/* src/App.js */
- import './App.css';
+ import './App.less';

/* src/App.less */
- @import '~antd/dist/antd.css';
+ @import '~antd/dist/antd.less';

然后安装 craco-less 并修改 craco.config.js 文件如下
yarn add craco-less

const CracoLessPlugin = require('craco-less');

module.exports = {
plugins: [
{
plugin: CracoLessPlugin,
options: {
lessLoaderOptions: {
lessOptions: {
modifyVars: { '@primary-color': '#1DA57A' },
javascriptEnabled: true,
},
},
},
},
],
};

支持装饰器语法和配置代理
yarn add @babel/plugin-proposal-decorators --dev //用来支持装饰器

//在craco.config.js文件下的module.exports添加如下代码
babel:{  
plugins: [
["@babel/plugin-proposal-decorators", { legacy: true }]
]
},

//配置代理解决跨域
devServer: {
proxy: {
"/api": {
target: "baidu.com",  
//target: 'http://192.168.9.19:8080',
changeOrigin: true,
pathRewrite: {
"^/api": ""
}
}
}
}

配置antd的less按需加载(则反打包后,会增大css文件)
yarn add babel-plugin-import

//在craco.config,.js里加上

babel:{  
plugins: [
["@babel/plugin-proposal-decorators", { legacy: true }],  //装饰器
[   
"import", 
{
"libraryName": "antd",
"libraryDirectory": "es",
"style": true //设置为true即是less
}
]
]
},

到App.less文件去掉@import '~antd/dist/antd.less';,
//按需加载后只需引入组件,无需再额外引入样式文件,babel会自动按需帮你完成样式的引入。这样打包出来的文件会更小。

配置别名
//在craco.config,.js里加上
const path = require('path');
module.exports = {
webpack: {
// 别名
alias: {
"@": path.resolve("src"),
"@utils": path.resolve("src/utils"),
}
},
}