Skip to content

Accessing env variables from index.html #3105

@eddeisling

Description

@eddeisling

Describe the bug

I try to insert html tag by environment variable condition and use vite-plugin-html for it. But Vite behaviour is weird

Reproduction

https://github.com/xSorc/test-vite-index-env

This code works only in build

<% if (import.meta.env.VITE_SHOW_TAG === '1') { %>
  works
<% } %>

During server i have this error

[vite] Internal server error: Cannot use 'import.meta' outside a module while compiling ejs
If the above error is not helpful, you may want to try EJS-Lint:
https://github.com/RyanZim/EJS-Lint
Or, if you meant to create an async function, pass `async: true` as an option.

This code works only in dev server

// vite.config.ts
require('dotenv').config();
// index.html
<% if (process.env.VITE_SHOW_TAG === '1') { %>
  works
<% } %>

But during build this doesn't work, because Vite replace process.env with this:

<% if (({}).VITE_SHOW_TAG === '1') { %>
  works
<% } %>
  1. The only option that works in both server and build is this:
// vite.config.ts
require('dotenv').config();
// index.html
<% if (process.env['VITE_SHOW_TAG'] === '1') { %>
  works
<% } %>

I suppose that first or second variant should works

System Info

Output of npx envinfo --system --npmPackages vite,@vitejs/plugin-vue --binaries --browsers:

  System:
    OS: Windows 10 10.0.19042
    CPU: (6) x64 Intel(R) Core(TM) i5-8600K CPU @ 3.60GHz
    Memory: 9.13 GB / 15.94 GB
  Binaries:
    Node: 14.15.3 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.10 - ~\AppData\Roaming\npm\yarn.CMD
    npm: 6.14.9 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Spartan (44.19041.423.0), Chromium (90.0.818.42)
    Internet Explorer: 11.0.19041.1
  npmPackages:
    vite: 2.2.1 => 2.2.1

Used package manager:


Before submitting the issue, please make sure you do the following

  • Read the Contributing Guidelines.
  • Read the docs.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Provide a description in this issue that describes the bug.
  • Make sure this is a Vite issue and not a framework-specific issue. For example, if it's a Vue SFC related bug, it should likely be reported to https://github.com/vuejs/vue-next instead.
  • Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Approved

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions