前端项目部署之后,运维可以自行修改配置文件里的接口IP,达到无需再次打包就可以使用的效果
vue2如何修改请看vue 部署后修改配置文件(接口IP)_vue部署后修改配置文件-CSDN博客
使用前提:
vite搭建的vue3项目 使用setup语法
需要借助一个插件生成配置文件
npm i vite-plugin-generate-file
env配置
如何配置查看vue .env配置环境变量_如何使用.env.development中定义的变量-CSDN博客
vite.config.js配置
import { fileURLToPath, URL } from 'node:url'
import { defineConfig,loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createHtmlPlugin } from "vite-plugin-html";
import generateFile from 'vite-plugin-generate-file'//读取所有当前环境的env
const getViteEnv = (mode, target) => {if(target==''){return loadEnv(mode, process.cwd());}else{return loadEnv(mode, process.cwd())[target];}};// https://vitejs.dev/config/
export default (res=> defineConfig({base: "", //等同于 assetsPublicPath :'./'plugins: [vue(),//修改网页的标题createHtmlPlugin({inject: {data: {title: getViteEnv(res.mode, "VITE_APP_Title"),},},}),//配置输出文件类型和内容generateFile([{type: 'json',output: './config.json',data:{_hash:new Date().getTime(),...getViteEnv(res.mode, '')}}])],resolve: {alias: {'@': fileURLToPath(new URL('./src', import.meta.url))}},build: {terserOptions: {compress: {keep_infinity: true,drop_console: true,drop_debugger: true,},},brotliSize: false,sourcemap: false,//分别打包rollupOptions: {output: {assetFileNames: assetInfo => {var info = assetInfo.name.split('.')var extType = info[info.length - 1]if (/\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/i.test(assetInfo.name)) {extType = 'media'} else if (/\.(png|jpe?g|gif|svg)(\?.*)?$/.test(assetInfo.name)) {extType = 'img'} else if (/\.(woff2?|eot|ttf|otf)(\?.*)?$/i.test(assetInfo.name)) {extType = 'fonts'}return `${extType}/[name]-[hash][extname]`},chunkFileNames: 'js/[name]-[hash].js',entryFileNames: 'js/[name]-[hash].js'}}},
})
)
读取配置:
<script setup>
import { onMounted } from "vue";
import { Empty} from "vant"
import axios from 'axios'onMounted(() => {getuserInfo()
});function getuserInfo(){axios({method: 'get',url: document.location.protocol +'//'+ window.location.host+window.location.pathname+'config.json',}).then(res=>{console.log('读取配置',res.data);})}</script><template><div><Empty description="读取用户信息中,请稍后..."></Empty></div>
</template>