create-react-app脚手架,用于快速搭建react项目。 初始化脚手架项目后会有如下提示
配置
生成config及script配置
使用npm run eject,对应目录下会生成config及script文件。
webpack-dev-server配置
host作用:配置服务器监听地址,默认是127.0.0.1,即只有本地可以访问对应http服务。如果让局域网内其他设备可访问本地服务,host上需要加上0.0.0.0 这里顺带说下样式上localhost、127.0.0.1、0.0.0.0区别 localhost:域名,指向的ip可修改 127.0.0.1:虚拟网卡 0.0.0.0:本网络中的本机
tsx支持
按照ts官方文档 描述新增node-modules
npm install --save-dev typescript awesome-typescript-loader source-map-loader
以及对应的tsconfig.json文件
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"jsx": "react"
},
"include": [
"./src/**/*"
]
}
运行项目依旧会报错
json文件新增配置
"esModuleInterop": true, "allowSyntheticDefaultImports": true,
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"module": "commonjs",
"target": "es5",
"jsx": "react"
},
"include": [
"./src/**/*"
]
}
proxy配置
proxy可以解决跨域问题,如下get请求,正常情况下是会访问到webpack-dev-server所创建的本地服务地址。但是往往需要的是后端服服务地址。 打开地址 http://localhost:3001/index.html,访问的地址是http://localhost:3001/api/aid/ip/info?version=1.1.1&src=Cashier
const getData=async()=>{
fetch('/api/aid/ip/info?version=1.1.1&src=Cashier', {
method: 'GET',
}).then(r=>{
console.log(r)
setData(data)
})
}
通过在webpackDevServer.config.js中配置proxy,在访问http://localhost:3001/api/aid/ip/info?version=1.1.1&src=Cashier 时,会被代理到mesh.if.iqiyi.com/api/aid/ip/… ,查看控制台可以看到对应的请求已经成功
proxy: {
'/api': {
target: "http://mesh.if.iqiyi.com",
changeOrigin: true,
secure: false,
pathRewrite: {
"^/api": "" // 这里是将/api改成空字符串
}
},
},