自学内容网 自学内容网

vue3+vite+ts中如何动态使用import.meta.env中的变量

1.使用场景

不想在使用import.meta.env的时候,还去找到变量文件去看

2. 使用插件的方式

1. 创建一个插件文件,根目录plugins/import-meta-env.d.ts

import type { Plugin } from "vite";
import { loadEnv } from "vite";
import path from "path";
import fsp from "fs/promises";

interface EnvOptions {
    prefix?: string;
    target?: string;
}

// 检查并创建目录
async function ensureDirectoryExists(dirPath: string): Promise<boolean> {
    try {
        // 尝试获取目录的状态
        await fsp.access(dirPath, fsp.constants.F_OK | fsp.constants.R_OK | fsp.constants.W_OK);
        return true;
    } catch (err: NodeJS.ErrnoException | any) {
        // 如果目录不存在,则创建目录
        if (err.code === "ENOENT") {
            try {
                await fsp.mkdir(dirPath, { recursive: true });
                return true;
            } catch (mkdirErr) {
                console.error(`创建目录失败: ${mkdirErr}`);
                return false;
            }
        } else {
            console.error(`访问目录时出错: ${err}`);
            return false;
        }
    }
}

export default function (options: EnvOptions = {}): Plugin {
    return {
        name: "vite-plugin-import-env-compatible",
        configResolved(config) {
            const mode = config.mode;
            const env = loadEnv(mode, process.cwd());
            let prefix = options.prefix || "VITE_";
            let target = options.target || "src/types/import-meta-env.d.ts";
            let dtsContent = `/// <reference types="vite/client" />\ninterface ImportMetaEnv {\n`;
            Object.keys(env).forEach((key) => {
                if (key.startsWith(prefix)) {
                    dtsContent += `    readonly ${key}: any; \n`;
                }
            });
            dtsContent += `}\n\n`;
            dtsContent += `interface ImportMeta { \n    readonly env: ImportMetaEnv \n}`;

            let dtsFilePath = path.resolve(process.cwd(), target);
            (async () => {
                let isSuccess = await ensureDirectoryExists(path.dirname(dtsFilePath));
                if (isSuccess) {
                    await fsp.writeFile(dtsFilePath, dtsContent);
                    console.log("import-meta-env.d.ts文件生成成功");
                }
            })();
        },
    };
}

2. 在vite.config.ts中引入

import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
import ImportMetaEnvCompatible from "./plugins/env-compatible.ts";

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
    loadEnv(mode, process.cwd(), "");
    return {
        envPrefix: "VITE_", // import.meta.env需要加载的前缀
        plugins: [vue(), ImportMetaEnvCompatible()],
        resolve: {
            alias: {
                "@": path.resolve(__dirname, "src"),
            },
        },
    };
});

3. 使用

这个时候在vue文件中使用的时候,就会有变量提示


原文地址:https://blog.csdn.net/weixin_45356397/article/details/143688647

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!