1

If I have an env file .env.development in the root directory, this works:

// .env.development
PUBLIC_FOO=foo

// foo.svelte
import { PUBLIC_FOO } from '$env/static/public';
...
console.log(PUBLIC_FOO); // works

However, if I have a custom env directory, it does not. But import.meta.env does work (for VITE_ properties as mentioned in the vite docs, but not PUBLIC_)

// 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); // does not work
console.log(import.meta.env.PUBLIC_FOO) // does not work
console.log(import.meta.env.VITE_FOO) // works

Update: I tried this too. Did not help:

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

1 Answer 1

2

Figured it out. The kit.env.dir property goes in svelte.config, not vite.config.

// svelte.config.js
const config = {
  preprocess: vitePreprocess(),
  kit: {
    adapter: adapter(),
    env: {
      dir: 'env',
    },
  },
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.