You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 10中Vite配置文件import.meta.env未定义错误求助

问题描述

我正在开发一个Laravel 10项目(搭配Vue2与Vite),需要在vite.config.js中使用APP_URL环境变量。我在.env文件中定义了:

VITE_APP_URL="${APP_URL}"

vite.config.js文件内容如下:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.js'],
            refresh: true,
        }),
    ],
    server: {
        https: false,
        host: true,
        hmr: {host: import.meta.env.APP_URL, protocol: 'ws'},
    }
});

但启动Vite服务器时出现错误:

10:41:55 AM [vite] Cannot read properties of undefined (reading 'APP_URL')
10:41:55 AM [vite] server restart failed

我尝试打印import.meta.env的值,结果为undefined。之后我创建了tsconfig.json并添加配置:

{
  "compilerOptions": {
    "types": ["vite/client"]
  }
}

但问题依旧存在。请问在vite.config.js中使用环境变量还需要哪些额外配置?是否可能是Vite未读取tsconfig.json导致的?

解决方案

核心问题:import.meta.env在Vite配置文件中不可用

import.meta.env是给前端代码(如Vue组件、JS模块)使用的,Vite配置文件本身是Node.js环境运行的脚本,不能直接用这个语法读取环境变量。

正确配置步骤

  1. 用Vite的loadEnv读取环境变量
    在vite.config.js中,需要通过Vite提供的loadEnv方法加载环境变量,修改后的配置文件如下:
import { defineConfig, loadEnv } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig(({ mode }) => {
    // 加载对应环境的.env文件,第二个参数指定.env所在目录(项目根目录)
    const env = loadEnv(mode, process.cwd());

    return {
        plugins: [
            laravel({
                input: ['resources/css/app.css', 'resources/js/app.js'],
                refresh: true,
            }),
        ],
        server: {
            https: false,
            host: true,
            // 使用加载到的环境变量
            hmr: { host: env.VITE_APP_URL, protocol: 'ws' },
        }
    };
});
  1. 修正.env文件的变量定义
    确保.env中已正确定义APP_URL,且VITE_APP_URL的写法无需转义引号:
APP_URL=http://your-local-domain.test
VITE_APP_URL="${APP_URL}"

Laravel会自动解析.env中的变量引用,这样就能把APP_URL的值正确传递给VITE_APP_URL。

  1. 关于tsconfig.json的说明
    你添加的vite/client类型配置,是给TypeScript代码提供import.meta.env的类型提示用的,和Vite配置文件本身的环境变量读取无关,这个配置没问题,但解决不了当前错误。

额外注意事项

  • 确保.env文件在项目根目录,且未被.gitignore意外排除(Laravel默认已配置正确的.gitignore规则)。
  • 修改.env文件后,必须重启Vite服务器才能生效。

内容的提问来源于stack exchange,提问作者Schrödinger's Cat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 05:53:13