Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 87 ยท Getting Started

Static Assets, Fonts, Images and Env Variables in Vite

Use images, fonts and environment variables in a Vue 3 Vite project: public versus src/assets, import URLs, @font-face, the @ alias, import.meta.env, .env files and image error handling.

A real app is more than components. It has a logo, photos, a custom font, an API address that differs between your laptop and production, and shortcuts that save you from writing ../../../components. In a project made with npm create vue@latest (Ways to use Vue) all of this goes through Vite, and a handful of rules explain everything.

The project files in this lesson are read-only, because the site's runner has no build step. The runnable examples show the Vue side of the same ideas: reacting to a broken image and choosing behaviour from environment values.

Two homes for files: public/ and src/assets/

Vite has two places for static files, and the difference matters.

public/ src/assets/ (any file you import)
How you refer to it By an absolute URL: /logo.svg By import or a relative path in a template or CSS
Processed by Vite No, copied as is Yes: bundled, small files may be inlined, big ones get a content hash in the name
Cache busting None, the name never changes Automatic, the hash changes when the file changes
Good for favicon.ico, robots.txt, files that outside systems must find at a fixed URL Images and fonts your components use

Prefer src/assets/ for anything a component uses. You get a hashed file name, so browsers can cache it for a year and still fetch the new version after a deploy. Use public/ only when the exact URL matters.

In a template, a relative path is handled by Vue's compiler and turned into an import:

VUE
<template>
  <!-- relative path: processed, hashed, bundled -->
  <img src="../assets/logo.svg" alt="Company logo">

  <!-- absolute path: served from public/, untouched -->
  <img src="/favicon.svg" alt="">
</template>

When the file name is dynamic, a relative string in a binding is not found at build time. Import the file, or build a URL with new URL:

VUE
<script setup>
import logoUrl from "../assets/logo.svg";          // a string such as "/assets/logo-3f2a9c.svg"

function avatar(name) {
  // Vite rewrites this pattern at build time, so every file that matches is included
  return new URL(`../assets/avatars/${name}.png`, import.meta.url).href;
}
</script>

<template>
  <img :src="logoUrl" alt="Logo">
  <img :src="avatar('ada')" alt="Ada">
</template>

The rule is that the folder part of the path must be written literally, so Vite knows which files to bundle. A completely variable path (new URL(someUserInput, ...)) cannot work.

The @ alias

Deep relative paths are fragile. The project from create-vue configures an alias in vite.config.js so that @ always means src/:

JavaScript
// vite.config.js
import { fileURLToPath, URL } from "node:url";
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
});

Now import BaseButton from "@/components/BaseButton.vue" works from any folder depth, and moving a file does not break its imports of shared modules. In templates and CSS the alias works with a leading @/ too (src="@/assets/logo.svg"). Editors need jsconfig.json or tsconfig.json to know the alias as well; create-vue writes that for you.

Fonts: @font-face and loading

Custom fonts are ordinary assets. Put the font files in src/assets/fonts/ (use woff2, it is the smallest and supported everywhere) and declare them in a stylesheet that your app imports once, for example in main.js:

CSS
/* src/assets/fonts.css */
@font-face {
  font-family: "Inter";
  src: url("./fonts/inter-var.woff2") format("woff2");
  font-weight: 100 900;      /* a variable font covers every weight */
  font-style: normal;
  font-display: swap;        /* show text immediately, swap when the font arrives */
}

body {
  font-family: "Inter", system-ui, -apple-system, "Segoe UI", sans-serif;
}
JavaScript
// src/main.js
import "./assets/fonts.css";

Vite resolves the url() relative to the CSS file and gives the font a hashed name. Four habits keep fonts fast:

  1. Subset and use woff2. Ship only the weights and scripts you really use.
  2. Always set font-display: swap (or optional) so that text is readable while the font downloads.
  3. Keep a fallback stack such as system-ui, sans-serif, so layout does not break if the font fails.
  4. Preload the one font that appears above the fold, with <link rel="preload" as="font" type="font/woff2" crossorigin href="..."> in index.html. Remember that public/ is the home for files you link by a fixed URL here.

Font packages from npm (such as @fontsource/inter) do the same thing with one import: import "@fontsource/inter/400.css".

Handling images that fail to load

Images are the one asset that fails at runtime: a URL from an API can be wrong, slow or gone. Show something sensible instead of a broken-image icon. The native error event works with Vue's @error, and loading="lazy" plus explicit width and height stop the page from jumping.

An image that falls back when it fails

The second tile points at a host that does not exist, so the browser fires error and the component switches src to the placeholder. Because the placeholder is a data URL and not the failing address, it cannot fail in a loop. Keep that guarantee in your own code: a fallback that can itself fail will trigger @error forever.

Knowing when an image has loaded

The opposite event is @load. Use it to show a skeleton while the image downloads and to hide it afterwards:

A loading state for an image

The image element is rendered but hidden with v-show (not v-if, which would stop it from loading), so the browser fetches it and fires load.

Environment variables: import.meta.env

Settings that change between environments, such as the API address, belong in .env files rather than in code. Vite reads these files at build time:

TEXT
.env                  loaded in every mode
.env.local            every mode, ignored by git
.env.development      only for `npm run dev` (mode "development")
.env.production       only for `npm run build` (mode "production")
Terminal
# .env.development
VITE_API_URL=http://localhost:3000/api
VITE_APP_TITLE=Shop (dev)

# .env.production
VITE_API_URL=https://api.example.com
DB_PASSWORD=this-never-reaches-the-browser

Only variables whose names start with VITE_ are exposed to your code, through import.meta.env:

JavaScript
const apiUrl = import.meta.env.VITE_API_URL;

if (import.meta.env.DEV) {
  console.log("running the dev server");   // removed from the production bundle
}

Vite also provides built-in values: import.meta.env.MODE ("development" or "production", or a custom mode from vite --mode staging), DEV, PROD, BASE_URL and SSR.

Everything in import.meta.env is replaced by its text at build time and ends up in the JavaScript that every visitor downloads. Never put secrets (passwords, private API keys, tokens) in a VITE_ variable. Anything the browser can read, a visitor can read. Secrets belong on a server that your frontend calls (security).

The sandbox cannot read .env files, so the next example uses a plain object with the same shape and shows the pattern you should follow: read the variables in one module, validate them there, and let the rest of the app import that module.

A config module built from import.meta.env (stand-in)

Switch between the two modes: the title, the API address and the debug panel all follow the environment, and the single loadConfig function is the only code that knows where the values come from. In a real project it would throw (or show an error page) when a required value is missing, so a bad deploy fails loudly at startup rather than with a mysterious 404 later.

Two last reminders. The .env files are read when Vite starts, so restart npm run dev after editing them. And because values are baked in at build time, the same built folder cannot be pointed at a different API without rebuilding; if you need that, load a small config.json from public/ at startup instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You need a file to be reachable at the fixed URL /robots.txt. Where does it go?

    Files in public/ are copied untouched, so /robots.txt works. Files in src/assets get hashed names and are meant to be imported by your code.
  2. 2. Which environment variable can your Vue code read with import.meta.env?

    Only names that start with VITE_ are exposed. Even so, they are compiled into the public bundle, so they must never hold secrets.
  3. 3. Why does src="../assets/avatars/" + name + ".png" in a template binding not work after the build?

    Vite finds assets at build time. For a dynamic name, import the files or use new URL(../assets/avatars/${name}.png, import.meta.url), which keeps the folder part literal.
  4. 4. What does font-display: swap do?

    swap avoids invisible text while the font downloads. The text first appears in the fallback font.

Summary

  • Use src/assets/ for files your components use (hashed, bundled) and public/ for files that need a fixed URL.
  • Relative paths in templates and CSS are processed; for dynamic names use imports or new URL(..., import.meta.url) with a literal folder.
  • The @ alias points at src/ and is configured in vite.config.js.
  • Declare fonts with @font-face (woff2, font-display: swap, a fallback stack) and import the stylesheet once.
  • Handle runtime image failures with @error, and give images fixed dimensions.
  • Only VITE_-prefixed variables reach the browser through import.meta.env, and they are public. Read them in one config module.

Next: how a Vue file is organized, Single-File Components.