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

自定义环境目录中$env/static/public为何无法正常生效?

SvelteKit自定义env目录下PUBLIC_前缀环境变量失效问题

根目录环境文件的正常情况

当.env.development文件放在项目根目录时,PUBLIC_FOO可以正常使用:

// .env.development
PUBLIC_FOO=foo

// foo.svelte
import { PUBLIC_FOO } from '$env/static/public';
...
console.log(PUBLIC_FOO); // 正常输出

自定义env目录下的异常情况

将环境文件移到自定义env目录后,上述方式失效。此时import.meta.env仅对VITE_前缀的变量生效,PUBLIC_前缀变量无论是通过$env/static/public导入还是直接访问import.meta.env.PUBLIC_FOO都无法正常工作:

// env/.env.development
PUBLIC_FOO=foo
VITE_FOO=foo

// vite.config.ts
export default defineConfig({
  plugins: [sveltekit()],
  envDir: 'env',
  test: {
    include: ['src/**/*.{test,spec}.{js,ts}'],
  }
});

// foo.svelte
import { PUBLIC_FOO } from '$env/static/public';
...
console.log(PUBLIC_FOO); // 无效
console.log(import.meta.env.PUBLIC_FOO) // 无效
console.log(import.meta.env.VITE_FOO) // 正常输出

已尝试的配置(未解决问题)

尝试了以下配置,但问题仍未解决:

export default defineConfig(({ mode }) => {
  loadEnv(mode, 'env', '');
  return {
    plugins: [sveltekit()],
    envDir: 'env',
    kit: {
      env: {
        dir: 'env',
      },
    },
    test: {
      include: ['src/**/*.{test,spec}.{js,ts}'],
    },
  };
});

内容的提问来源于stack exchange,提问作者Joe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 01:52:44