如何将 dotenv 与 vite/petite vue 一起使用?

Lor*_*aco 5 environment-variables typescript vue.js

如何.env在项目中使用变量petite-vue?运行时yarn vite给我错误:process is not defined

文件结构是这样的:

Root
|_index.html
|_vue-index.ts
Run Code Online (Sandbox Code Playgroud)

我已经导入了 vue 脚本,index.html并且console.log('Hello')连接到按钮之类的东西工作正常,所以这不是导入脚本的问题。但是,当我尝试时,console.log(process.env.URL)它会返回该错误,并且 @click 不会执行任何操作。

Root
|_index.html
|_vue-index.ts
Run Code Online (Sandbox Code Playgroud)
# .env
URL=http://example.com
Run Code Online (Sandbox Code Playgroud)

问题似乎是import.meta.env.自然而然地出现的。我的问题是,对于 TS,如果不将tsconfig.jsonmoule 选项更改为esnext或其他,则不允许这样做。

有人可以解释我如何使用它吗?如果我运行ts-node正常的话。

// vue-index.ts
import { createApp } from 'petite-vue';
import 'dotenv/config';

createApp({
  print() {
   console.log(process.env.API_URL);
  },
}).mount('#app');
Run Code Online (Sandbox Code Playgroud)

小智 6

.env1-在您的主目录中创建文件。它不在文件夹中/src

2-在Vite + Vue 3VITE_中只能访问文件中以开头的键。.env

.env文件内容示例

VITE_BACKEND_PORT = 5000
VITE_MAP_KEY = eae5454ii5557772142
BACKEND_PORT = itIsInaccessible
Run Code Online (Sandbox Code Playgroud)

App.vue在文件中使用的示例

<script setup>
const backendPort = import.meta.env.VITE_BACKEND_PORT;
const mapKey = import.meta.env.VITE_MAP_KEY;
console.log(backendPort)
console.log(mapKey)
</script>
<template>
{{backendPort}} {{mapKey}}
</template>
Run Code Online (Sandbox Code Playgroud)


Lor*_*aco 2

对于来这里寻求解决问题的人,我发现最简单的方法就是使用这个插件。

只需将这几行添加到 vite.config.*

// vite.config.ts
import EnvironmentPlugin from 'vite-plugin-environment'; // Here we import the plugin that expose env variable when vite bundle up the app

const config = {
  root: './src',

  // Here you can define which env to expose with prefix params
  // i.e.: EnvironmentPlugin('all', {prefix: 'test'}) => test_env_var == true, env_var == false
  plugins: [EnvironmentPlugin('all', {prefix: ''})], 
};

export default config;

Run Code Online (Sandbox Code Playgroud)