React Vite无法读取VSCode launch.json中的环境变量求助
问题根源
VSCode launch.json 中的 env 配置是给Chrome浏览器进程设置环境变量的,但Vite的环境变量是在Node.js环境下的开发服务启动阶段注入到代码中的。这两个属于完全独立的进程,所以浏览器的环境变量根本不会被Vite捕获到,自然读不到 VITE_TEST。
解决方案
下面提供几种可行的解决方式,按需选择:
方法一:通过预启动任务传递环境变量
先定义一个带环境变量的Vite启动任务,再让Chrome调试依赖这个任务:
- 在
.vscode/tasks.json中添加任务:
{ "version": "2.0.0", "tasks": [ { "label": "vite-dev-with-env", "type": "shell", // Windows系统使用:set VITE_TEST=12345 && npm run dev "command": "VITE_TEST=12345 npm run dev", "isBackground": true, "problemMatcher": { "background": { "activeOnStart": true, "beginsPattern": "VITE v\\d+ ready in", "endsPattern": "Local: http://localhost:5173" } } } ] }
- 修改
launch.json,添加预启动任务并移除原来的env配置:
{ "version": "0.2.0", "configurations": [ { "type": "chrome", "request": "launch", "name": "Launch Chrome", "url": "http://localhost:5173", "webRoot": "${workspaceFolder}", "sourceMaps": true, "resolveSourceMapLocations": [ "${workspaceFolder}/**", "!**/node_modules/**" ], "preLaunchTask": "vite-dev-with-env" } ] }
方法二:使用Vite的多环境配置文件
利用Vite的模式加载机制,专门给调试环境创建配置文件:
- 创建
.env.debug文件:
VITE_TEST=12345
- 在
package.json的scripts中添加调试命令:
{ "scripts": { "dev": "vite", "dev:debug": "vite --mode debug" } }
- 修改
launch.json的预启动任务,指向这个新脚本:
{ "version": "0.2.0", "configurations": [ { "type": "chrome", "request": "launch", "name": "Launch Chrome", "url": "http://localhost:5173", "webRoot": "${workspaceFolder}", "sourceMaps": true, "resolveSourceMapLocations": [ "${workspaceFolder}/**", "!**/node_modules/**" ], "preLaunchTask": "npm: dev:debug" } ] }
方法三:直接启动Vite服务(Node调试模式)
用Node类型的配置启动Vite并设置环境变量,再附加Chrome调试:
{ "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Start Vite Dev Server", "program": "${workspaceFolder}/node_modules/vite/bin/vite.js", "env": { "VITE_TEST": "12345" }, "console": "integratedTerminal" }, { "type": "chrome", "request": "attach", "name": "Attach Chrome", "port": 9222, "webRoot": "${workspaceFolder}", "sourceMaps": true, "resolveSourceMapLocations": [ "${workspaceFolder}/**", "!**/node_modules/**" ] } ], "compounds": [ { "name": "Vite + Chrome Debug", "configurations": ["Start Vite Dev Server", "Attach Chrome"] } ] }
运行这个复合配置,会自动先启动带环境变量的Vite服务,再附加Chrome调试。
验证方式
修改代码打印完整的环境变量对象,确认 VITE_TEST 是否存在:
console.log('All Vite env variables:', import.meta.env);
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

