一、跨域
1 请求的url
后端的apiurl都是这样的格式 https://test.com/api/login
https://test.com/api/home
2 proxy配置
/vite.config.ts 文件
export default defineConfig({
server: {
port: 8080,
open: true,
proxy: {
'/api': {
target: 'https://test.com', //跨域地址
changeOrigin: true //支持跨域
//因为我的url地址本来就有/api所以没有重写
}
}
},
})
/.env文件
VITE_APP_BASE_API=https://test.com/api
3 axios配置
因为我封装了axios,所以在**/api/request.ts**文件里
const service = axios.create({
baseURL: import.meta.env.VITE_APP_BASE_API,
timeout: 15000
})
//请求拦截器。。等配置
二、打包
1 npm run build
运行后发现有很多ts的语法错误提示,于是关掉ts的检查
/package.json文件,build改为“vite build”
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
2 本地服务器运行打包后的文件
安装http-server
npm install http-server -g //全局安装。
终端切换到打包后的目录,运行
cd .\dist\
http-server
运行结果:
Starting up http-server, serving ./
http-server version: 14.1.1
http-server settings:
CORS: disabled
Cache: 3600 seconds
Connection Timeout: 120 seconds
Directory Listings: visible
AutoIndex: visible
Serve GZIP Files: false
Serve Brotli Files: false
Default File Extension: none
Available on:
http://192.168.9.55:8080
http://127.0.0.1:8080
Hit CTRL-C to stop the server
3 json资源处理
我用了echarts的地图,json文件下载在/src/assets/map
里,打包后却发现 地图没显示出来,其他图表可以显示
看提示信息:http://127.0.0.1:8080/src/assets/map/%E4%B8%AD%E5%8D%8E%E4%BA%BA%E6 没有找到
,是路径问题;而且打包后的文件夹里也没有这些资源。
/vite.config.ts文件 ,设置静态资源目录,就是打包时候去这个文件夹里找静态资源,这个目录中的文件(如HTML、图片、字体文件等)会被直接复制到输出目录(通常是dist)中,并且在开发服务器上可通过根URL访问。
export default defineConfig({
publicDir:'./src/assets',//
//省略
})
这时候打包就会在dist里发现有map文件夹下的json文件
同时也要修改组件里引用json文件的路径,直接前面的文件夹不用写了,因为publicDir已经写过了
const pathFiles = {
北京市: '/map/北京市.json',
天津市: '/map/天津市.json',
河北省: '/map/河北省.json',
山西省: '/map/山西省.json',
太原市: '/map/山西省/太原市.json',
大同市: '/map/山西省/大同市.json',
阳泉市: '/map/山西省/阳泉市.json',
长治市: '/map/山西省/长治市.json',
晋城市: '/map/山西省/晋城市.json',
。。。。
}