kit: Environment variables in Svelte templates don't work with `npm run build`

First of all, thank you for the great work on SvelteKit. I migrated my blog today without too many problems, the docs, the migration guide and examples were a great help. I just stumbled upon this problem.

Describe the bug

It seems like we can’t use environment variables (e.g. import.meta.env.MODE) in a (production) build while there are also styles defined in the same route/component.

It does however work when I start the server and open the app with npm run dev

I also tried to follow the vite docs, but sadly with the same outcome. Logs

$ svelte-kit build
vite v2.1.3 building for production...
✓ 15 modules transformed.
.svelte/output/client/_app/manifest.json                            0.67kb
.svelte/output/client/_app/assets/start-a8cd1609.css                0.16kb / brotli: 0.10kb
.svelte/output/client/_app/pages\index.svelte-91d77487.js           0.56kb / brotli: 0.33kb
.svelte/output/client/_app/assets/pages\index.svelte-c8d90d46.css   0.03kb / brotli: 0.03kb
.svelte/output/client/_app/chunks/index-5061b396.js                 4.60kb / brotli: 1.83kb
.svelte/output/client/_app/start-c78a3e4f.js                        15.25kb / brotli: 5.31kb
vite v2.1.3 building SSR bundle for production...
✓ 8 modules transformed.
file: C:/Users/tdeschryver/dev/poc/sk-environment-variables/src/routes/index.svelte:6:131
> Unexpected token (6:131)
    at Object.pp$4.raise (C:\Users\tdeschryver\dev\poc\sk-environment-variables\node_modules\rollup\dist\shared\rollup.js:15614:13)
    at Object.pp.unexpected (C:\Users\tdeschryver\dev\poc\sk-environment-variables\node_modules\rollup\dist\shared\rollup.js:13306:8)
    at Object.pp.expect (C:\Users\tdeschryver\dev\poc\sk-environment-variables\node_modules\rollup\dist\shared\rollup.js:13300:26)
    at Object.pp$3.parseObj (C:\Users\tdeschryver\dev\poc\sk-environment-variables\node_modules\rollup\dist\shared\rollup.js:15250:12)
    at Object.pp$3.parseExprAtom (C:\Users\tdeschryver\dev\poc\sk-environment-variables\node_modules\rollup\dist\shared\rollup.js:14989:17)
    at Object.pp$3.parseExprSubscripts (C:\Users\tdeschryver\dev\poc\sk-environment-variables\node_modules\rollup\dist\shared\rollup.js:14816:19)
    at Object.pp$3.parseMaybeUnary (C:\Users\tdeschryver\dev\poc\sk-environment-variables\node_modules\rollup\dist\shared\rollup.js:14793:17)
    at Object.parseMaybeUnary (C:\Users\tdeschryver\dev\poc\sk-environment-variables\node_modules\rollup\dist\shared\rollup.js:19538:29)
    at Object.pp$3.parseExprOps (C:\Users\tdeschryver\dev\poc\sk-environment-variables\node_modules\rollup\dist\shared\rollup.js:14728:19)
    at Object.pp$3.parseMaybeConditional (C:\Users\tdeschryver\dev\poc\sk-environment-variables\node_modules\rollup\dist\shared\rollup.js:14711:19)
error Command failed with exit code 1.

To Reproduce

A reproduction can be found at: https://github.com/timdeschryver/sk-environment-variables/blob/main/src/routes/index.svelte

Steps to reproduce:

git clone https://github.com/timdeschryver/sk-environment-variables.git
cd sk-environment-variables
cd ./sk-environment-variables
npm install
npm run build

The code:

<script>
	let variable = import.meta.env.MODE
</script>

<main>
	<h1>Variable: {variable}</h1>
</main>

<!-- comment or remove styles and it works -->
<style>
	h1 {
		color:red
	}
</style>

Expected behavior

I expect the environment variable to be replaced.

Information about your SvelteKit Installation:

  • The output of npx envinfo --system --npmPackages svelte,@sveltejs/kit --binaries --browsers
  System:
    OS: Windows 10 10.0.19042
    CPU: (8) x64 Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz
    Memory: 4.24 GB / 15.85 GB
  Binaries:
    Node: 14.16.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.5 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 6.14.11 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Chrome: 89.0.4389.90
    Edge: Spartan (44.19041.423.0), Chromium (89.0.774.63)
    Internet Explorer: 11.0.19041.1
  npmPackages:
    @sveltejs/kit: next => 1.0.0-next.61
    svelte: ^3.29.0 => 3.35.0
  • Your adapter (e.g. Node, static, Vercel, Begin, etc…)

I get the error with all adapters, node, static, and vercel.

Severity

I have a workaround (I added the variables to a GET request), but I still wanted to log this issue because it might help others.

Additional context

/

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 9
  • Comments: 21 (10 by maintainers)

Commits related to this issue

Most upvoted comments

This is a tricky issue and I’m not immediately sure what the best fix is, but a workaround in the meantime would be to put the env var references in a module (rather than a component) and import them into your components:

export const API_URL = import.meta.env.VITE_API_URL;

For reference, here’s the code that’s being generated in @arxpoetica’s example

/* src/routes/index.svelte generated by Svelte v3.43.1 */
import { create_ssr_component, escape } from "svelte/internal";

const css = {
	code: "div.s-Uap-jPRb-uiE{color:red}.s-Uap-jPRb-uiE{}",
	map: "{\"version\":3,\"file\":\"index.svelte\",\"sources\":[\"index.svelte\"],\"sourcesContent\":[\"<div>{console.log("testing")}</div>\\n<div>{"testing"}</div>\\n\\n<style>\\n\\tdiv {\\n\\t\\tcolor: red;\\n\\t}\\n *{}</style>\\n\"],\"names\":[],\"mappings\":\"AAIC,GAAG,eAAC,CAAC,AACJ,KAAK,CAAE,GAAG,AACX,CAAC,AACD,eAAC,EAAE\"}"
};

const Routes = create_ssr_component(($$result, $$props, $$bindings, slots) => {
	$$result.css.add(css);

	return `<div class="${"s-Uap-jPRb-uiE"}">${escape(console.log("testing"))}</div>
<div class="${"s-Uap-jPRb-uiE"}">${escape("testing")}</div>`;
});

export default Routes;
import "/src/routes/index.svelte?svelte&type=style&lang.css";

It’s the css.map that’s causing trouble, and I thought it’d be useful to see an example of it in this issue

@Rich-Harris - Thanks for the tip, its working great!

@timdeschryver - The trick is as @Rich-Harris mentions, “import them into your components”. It looks like you are adding the module to the same component, that didn’t work for me. Make a separate module and import it. Also you are spot on about it working when you remove the style block. By making the separate module and importing we can leave out the style block which is breaking it.

This is what’s working for me with v1.0.0-next.71

src/lib/env/Env.svelte

<script context="module">
	export const API_DOMAIN = import.meta.env.VITE_PUBLIC_API_DOMAIN
</script>

src/lib/components/Comp1.svelte

<script>
	import { API_DOMAIN } from '$lib/env/Env.svelte'
</script>

<div class="">{API_DOMAIN}</div>

<style>
	div {
		background: lightsalmon;
	}
</style>

@benmccann it seems like it does work, I’ve created the same component in this repro.

I can build and serve the app, the environment variable import.meta.env.MODE is assigned to production.

AFAIK nothing new, but the suggested workaround works like a charm.

Avoiding dot notation with environment variables fixed the issue for me.