react脚手架配置代理与路径别名
宋宇 2020-12-06 react
# react 脚手架常见配置
# 一、配置代理:
- 简单版配置: package.json 中直接添加:"proxy": "http://localhost:4000"
- 完整版本配置:
(1).下载:yarn add http-proxy-middleware
(2).在 src 目录下创建:setupProxy.js,内容如下:
const proxy = require('http-proxy-middleware') module.exports = function(app) { app.use( //带有api是需要转发的请求 proxy.createProxyMiddleware('/api', { // 这里是服务器地址 target: 'http://localhost:4000', //值为布尔值, 为true时, 本地就会虚拟一个服务器接收你的请求并代你发送该请求, changeOrigin: true, pathRewrite: {'^/api': ''} }) ) }
1
2
3
4
5
6
7
8
9
10
11
12
13 - 备注:react脚手架的配置代理后,在请求资源时会优先请求前端资源,若没有再请求后端资源。
# 二、配置路径别名:
- 下载 customize-cra 库:yarn add customize-cra
- 项目根目录下建立:config-overrides.js,内容如下:
const {addWebpackAlias} = require('customize-cra');
const { resolve } = require("path");
module.exports = override(
addWebpackAlias({
"@": resolve(__dirname, "src")
})
);
1
2
3
4
5
6
7
2
3
4
5
6
7
- 为了能让vscode依然能提示路径,项目根路径建立:jsconfig.json,内容如下:
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
}
},
"exclude": ["node_modules", "dist"]
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9