vue3.0 vite中使用环境变量

492 阅读1分钟

import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
import styleImport, { VantResolve } from "vite-plugin-style-import";
import { createHtmlPlugin } from "vite-plugin-html";

//这个配置 为了在html中使用 环境变量
const getViteEnv = (mode: string, env: string) => {
  return loadEnv(mode, process.cwd())[env];
};

export default ({ mode }) =>
  defineConfig({
    base: getViteEnv(mode, 'VITE_CONTEXT_PATH'),
    plugins: [
      vue(),
      styleImport({
        resolves: [VantResolve()],
        libs: [
          {
            libraryName: "vant",
            esModule: true,
            resolveStyle: (name) => {
              return `../es/${name}/style/index`;
            },
          },
        ],
      }),
      createHtmlPlugin({
        inject: {
          data: {
            //将环境变量 VITE_APP_TITLE 赋值给 title 方便 html页面使用 title 获取系统标题
            title: getViteEnv(mode, "VITE_APP_TITLE"),
          },
        },
      }),
    ],
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "src"),
        assets: path.resolve(__dirname, "src/assets"),
      },
    },
   
  });