如何在.env项目中使用petite-vue变量?当运行yarn vite时,它会给出错误:process is not defined
文件结构如下:
Root
|_index.html
|_vue-index.ts我已经在index.html中导入了vue脚本,并且使用console.log('Hello')之类的连接到按钮的东西可以很好地工作,所以导入脚本就没有问题了。但是,当我尝试console.log(process.env.URL)时,它会返回错误并@click不要做任何事情。
# .env
URL=http://example.com// vue-index.ts
import { createApp } from 'petite-vue';
import 'dotenv/config';
createApp({
print() {
console.log(process.env.API_URL);
},
}).mount('#app');问题似乎在于vite的import.meta.env. things。我的问题是,在TS中,如果不将tsconfig.json鼠标选项更改为esnext或其他选项,就不允许使用任何东西。
有人能解释我怎么用它吗?如果我用ts-node运行这个程序,就可以正常工作。
import 'dotenv/config'
console.log(processs.env.API_URL)发布于 2022-05-31 20:50:52
1-在主目录中创建.env文件。它是而不是在/src文件夹中。
只有以VITE_开头的键可以在.env文件中从Vite + Vue 3中访问。
示例.env文件内容
VITE_BACKEND_PORT = 5000
VITE_MAP_KEY = eae5454ii5557772142
BACKEND_PORT = itIsInaccessibleApp.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>发布于 2022-02-01 08:08:10
对于来这里寻求解决问题的人来说,我发现最简单的方法是使用这插件。
只需将这几行添加到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;https://stackoverflow.com/questions/70929227
复制相似问题