Vite项目中import.meta.env.MODE在Playwright运行时报错求助
解决Playwright运行时
import.meta.env.MODE未定义的问题 问题根源
Playwright运行时没有经过Vite的环境变量注入流程,而Vitest默认会模拟Vite的环境变量,所以前者报错后者正常。Vite在开发/构建阶段会将import.meta.env相关代码替换为实际值,直接运行未处理的源码会导致变量未定义。
解决思路
1. 让Playwright依赖Vite开发服务
在playwright.config.ts中配置webServer,让Playwright启动并连接到Vite的开发服务器,确保页面加载的是经过Vite处理的代码:
// playwright.config.ts import { defineConfig, devices } from '@playwright/test'; export default defineConfig({ webServer: { command: 'npm run dev', // 你的Vite启动命令 url: 'http://localhost:5173', // 对应Vite配置的端口 reuseExistingServer: !process.env.CI, // CI环境下每次重启,本地复用已有服务 }, use: { baseURL: 'http://localhost:5173', // 测试时直接用这个baseURL访问页面 }, // 其他Playwright配置... });
2. 为生产构建后的代码做校验
如果是测试生产构建产物,确保执行vite build后,dist目录中的代码已经将import.meta.env替换为实际值。检查package.json的build命令是否为标准的vite build,构建后再用Playwright加载dist内的文件。
3. 给环境变量添加 fallback 避免报错
修改constants.ts,对import.meta.env的访问添加可选链或默认值,防止变量未定义时抛出错误:
// constants.ts let rootUrl = API_ENV.staging // 给MODE添加默认值,避免未定义 if ((import.meta.env.MODE ?? 'development') === 'production') { rootUrl = API_ENV.prod } // 给VITE_SERVER添加默认空字符串 const server = import.meta.env.VITE_SERVER ?? ''; const localFlags = ['localhost', 'local', 'l'] if (server) { // 直接判断server是否有值 if (localFlags.includes(server)) { rootUrl = API_ENV.localhost } else { rootUrl = server } }
4. 组件测试(Component Testing)的特殊配置
如果用Playwright做组件测试(@playwright/experimental-ct-react),需要在playwright-ct.config.ts中配置Vite环境变量:
// playwright-ct.config.ts import { defineConfig } from '@playwright/experimental-ct-react'; export default defineConfig({ testDir: './tests', viteConfig: { define: { 'import.meta.env.MODE': JSON.stringify(process.env.NODE_ENV ?? 'development'), 'import.meta.env.VITE_SERVER': JSON.stringify(process.env.VITE_SERVER ?? ''), }, }, });
内容的提问来源于stack exchange,提问作者Shannon Smith
相关产品推荐
相关产品推荐

