question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

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

See original GitHub issue

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

/

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:8
  • Comments:21 (10 by maintainers)

github_iconTop GitHub Comments

10reactions
Rich-Harriscommented, Apr 2, 2021

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;
2reactions
benmccanncommented, Oct 11, 2021

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

Read more comments on GitHub >

github_iconTop Results From Across the Web

Environment variables in svelte + rollup - Stack Overflow
I'm using svelte with rollup straight from sveltejs/template. It should be simple but I see no way of doing it. It's cumbersome, but...
Read more >
Using environment variables in SvelteKit (and Vite)
Setting environment variables in SvelteKit is as simple as creating a .env file ... It crashes for you on npm run build ?...
Read more >
Docs • Svelte
With this, npm run build will generate HTML, JS and CSS files inside the dist directory.
Read more >
Dynamic behavior in Svelte: working with variables and props
svelte component is currently just displaying static markup; let's start making it a bit more dynamic. We'll take the tasks information from the ......
Read more >
Env Variables and Modes - Vite
For example, dynamic key access like import.meta.env[key] will not work. ... For example, when running VITE_SOME_KEY=123 vite build . .env files are loaded ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found