vite 使用 process.env

.env.development

VITE_HOST = '127.0.0.1'
VITE_PORT = 3003
VITE_BASE_URL = './'
VITE_OUTPUT_DIR = 'dist1'
VITE_API_DOMAIN = 'http://ip:8080/' //本地环境地址(可用于开发时联调)

 .env.production

VITE_HOST = '127.0.0.1'
VITE_PORT = 3005
VITE_BASE_URL = './'
VITE_OUTPUT_DIR = 'dist'
VITE_API_DOMAIN = 'http://ip:8080/'

vite.config.js

import vue from '@vitejs/plugin-vue'
import {defineConfig, loadEnv} from "vite";

export default ({command, mode}) => {
    const envConfig = loadEnv(mode, './');
    let config = {
        base: './',
        plugins: [vue()],
        optimizeDeps: {
            include: ['schart.js']
        },
        server: {
            host: envConfig.VITE_HOST,
            port: envConfig.VITE_PORT,
            // 是否自动在浏览器打开
            open: true,
            // 是否开启 https
            https: false,
            // 服务端渲染
            ssr: false,
            base: envConfig.VITE_BASE_URL,
            outDir: envConfig.VITE_OUTPUT_DIR,
            define: {
                'process.env': {}
            }
        },
    };

    return defineConfig(config)
}

package.json

"scripts": {
    "dev": "vite --mode development",
    "test": "vite  --mode testing",
    "prod": "vite  --mode production",
    "serve": "vite preview"
  },

引入环境配置

import.meta.env.VITE_API_DOMAIN

  

posted on 2021-12-22 15:14  书梦一生  阅读(8435)  评论(0编辑  收藏  举报

导航