My project is created using CRA (create-react-app), so this article is only for projects built in this way
During development, in order to make the import path shorter, alias is usually used, for example, ../../../components/Button
it will be @/components/Button
used as a replacement.
Seen
In Vue, use vue.config.js
to modify the webpack configuration. And most of the writing methods are the same as webpack, and the proxy including the interface is also written in it. After the configuration is completed, the service can be started directly.
// vue.config.js
vueConfig = {
...
chainWebpack: (config) => {
config.resolve.alias
.set('@$', resolve('src'))
},
devServer: {
proxy: {
'/api': {
target: 'host',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
复制代码
This is a common vue project configuration with an alias set to @
; a proxy that listens for /api
requests starting with , and redirects the proxy to the host
address, which will be /api
rewritten as ''
.
The advantage of this configuration together is that it is very convenient to modify the content, and when someone takes over the project, they can see some previous configuration information at a glance.
React
Alias
When I wrote the react project for the first time, following the logic of the same origin, I searched the project and found no relevant configuration files, so I had to ask the all-powerful Google for help.
There are roughly two solutions found on the Internet:
npm run eject
Release the default configuration for modification;- Use
react-app-rewired
craco
plugins like this to create additional files for configuration mixins;
In addition to these two common ones, there is actually one of the easiest ways: js(ts)config.json
{
...
"baseUrl": "./src",
"paths": {
"@/*": ["*"]
}
}
复制代码
The key point is in these two fields
baseUrl
: Specifies the root directory of the access path. For example src/views/Index/Index
, if the access path is src, the access path can be written as views/Index/Index
;
paths
: It is simply understood as specifying an alias, and the access path of the alias bashUrl
is specified; in fact, it is often referred to as alias, but the writing method is not the same; here is to specify an alias @
, and the access path is the src directory.
Proxy
官方的推荐为,简单配置可直接在package.json
里增加proxy字段,并赋值为字符串;复杂的使用http-proxy-middleware
进行配置,创建src/setupProxy.js
文件进行配置;
如果看过react打包时执行的代码的话,会产生一个问题,为什么基础配置只支持字符串,明明代码里只是获取package.json
里的proxy字段进行合并。
于是我尝试改造我的package.json
,将proxy的配置写入
{
...
"proxy": {
"/api": {
"target": "host",
"ws": false,
"changeOrigin": true,
"pathRewrite": {
"^/api": ""
}
}
},
}
复制代码
然而在我执行yarn start
时,控制台会提示When specified, "proxy" in package.json must be a string. Instead, the type of "proxy" was "object". Either remove "proxy" from package.json, or make it a string.
。我在配置文件内根本找不到这个提示,突然想到,会不会是在依赖里。经过搜索后,发现react-dev-utils/WebpackDevServerUtils.js
有类型判断。
其实我这里不是很懂,react为什么不把配置给放开,这样相对来说会简单一些,希望大佬能在评论区给我一些解答。
至此,react项目的基本开发配置就完成,接下来就可以正式进入开发