阿里云主机折上折
  • 微信号
Current Site:Index > Custom HTML template

Custom HTML template

Author:Chuan Chen 阅读数:13248人阅读 分类: 构建工具

Project Configuration and Basic Usage Custom HTML Templates

Vite.js allows developers to customize HTML templates, which is useful when modifying the default HTML structure or injecting specific content. By default, Vite uses a built-in HTML template, but it can be easily overridden with simple configuration.

Basic Configuration Method

Creating an index.html file in the project root directory automatically makes it the entry template for the application. Vite will process this file and automatically inject the necessary script tags. A basic custom HTML template looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Vite App</title>
</head>
<body>
  <div id="app"></div>
  <script type="module" src="/src/main.js"></script>
</body>
</html>

Template Variables and Interpolation

Vite's HTML templates support special %ENV_VAR% syntax to inject environment variables:

<title>%VITE_APP_TITLE%</title>

These variables can be defined in vite.config.js using the define option:

export default defineConfig({
  define: {
    'import.meta.env.VITE_APP_TITLE': JSON.stringify('My App')
  }
})

Multi-Page Application Configuration

For multi-page applications, configure multiple entry points in vite.config.js:

import { resolve } from 'path'

export default defineConfig({
  build: {
    rollupOptions: {
      input: {
        main: resolve(__dirname, 'index.html'),
        about: resolve(__dirname, 'about.html'),
        contact: resolve(__dirname, 'contact.html')
      }
    }
  }
})

Each HTML file corresponds to an independent page entry.

Dynamic Template Generation

For more complex scenarios, use the transformIndexHtml hook to dynamically modify HTML:

export default defineConfig({
  plugins: [
    {
      name: 'html-transform',
      transformIndexHtml(html) {
        return html.replace(
          /<title>(.*?)<\/title>/,
          `<title>Replaced Title</title>`
        )
      }
    }
  ]
})

Resource References in Templates

Vite automatically handles resource paths referenced in HTML:

<!-- Reference an image in the public directory -->
<img src="/logo.png" alt="Logo">

<!-- Reference an image in the src/assets directory -->
<img src="@/assets/icon.png" alt="Icon">

Conditional Content Injection

Inject different content based on environment variables:

<% if (import.meta.env.MODE === 'development') { %>
  <script src="https://cdn.example.com/dev-tools.js"></script>
<% } %>

Custom Template Location

If the HTML template is not in the project root, specify its location in the configuration:

export default defineConfig({
  root: 'src',
  publicDir: '../public',
  build: {
    outDir: '../dist'
  }
})

CSS Handling in Templates

Vite automatically processes CSS files referenced in HTML:

<!-- Injects HMR client in development -->
<link rel="stylesheet" href="/src/styles/main.css">

Server-Side Rendering (SSR) Configuration

For SSR applications, HTML templates require special handling:

export default defineConfig({
  ssr: {
    noExternal: true
  }
})

Internationalization Support

Add multi-language support in HTML templates:

<html lang="%VITE_APP_LANG%">

Then define the default language in the configuration:

export default defineConfig({
  define: {
    'import.meta.env.VITE_APP_LANG': JSON.stringify('en-US')
  }
})

Performance Optimization Configuration

Add preload hints via HTML templates:

<!-- Preload critical resources -->
<link rel="modulepreload" href="/src/main.js">

Security-Related Configuration

Add CSP meta tags:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'">

Mobile Adaptation

Add mobile-specific meta tags:

<meta name="theme-color" content="#ffffff">
<meta name="apple-mobile-web-app-capable" content="yes">

PWA Support

Add manifest link for PWA:

<link rel="manifest" href="/manifest.json">

Custom Favicon

Configure multi-sized favicons:

<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">

Template Validation

Add HTML validation-related meta tags:

<meta name="generator" content="Vite">

Social Media Sharing Optimization

Add Open Graph protocol tags:

<meta property="og:title" content="%VITE_APP_TITLE%">
<meta property="og:type" content="website">

Template Fragment Reuse

Dynamically insert reusable HTML fragments via JavaScript:

// Insert navigation bar at build time
const navHTML = await fs.readFile('src/partials/nav.html', 'utf-8')
export default defineConfig({
  plugins: [
    {
      transformIndexHtml: {
        transform(html) {
          return html.replace('<!-- nav-placeholder -->', navHTML)
        }
      }
    }
  ]
})

Build-Time Variable Replacement

Use @rollup/plugin-replace for more complex variable replacement:

import replace from '@rollup/plugin-replace'

export default defineConfig({
  plugins: [
    replace({
      __BUILD_DATE__: new Date().toISOString(),
      preventAssignment: true
    })
  ]
})

Then use it in HTML:

<footer>Build Date: __BUILD_DATE__</footer>

Template Cache Control

Add version numbers to static resources to prevent caching:

<script src="/main.js?v=%VITE_APP_VERSION%"></script>

Custom Error Pages

Create a custom 404 page:

<!-- 404.html -->
<!DOCTYPE html>
<html>
<head>
  <title>Page Not Found</title>
</head>
<body>
  <h1>404 - Page Does Not Exist</h1>
</body>
</html>

Template Compression Configuration

Configure HTML compression options:

export default defineConfig({
  build: {
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true
      }
    }
  }
})

Environment-Specific Content

Inject different content based on the environment:

<% if (import.meta.env.PROD) { %>
  <script src="https://cdn.example.com/analytics.js"></script>
<% } %>

SVG Handling in Templates

Use SVG directly in HTML:

<div>
  ${require('@/assets/logo.svg')}
</div>

Web Components in Templates

Support using Web Components directly in HTML:

<my-component></my-component>

Template Debugging Tips

Add development-specific debugging tools:

<% if (import.meta.env.DEV) { %>
  <script>
    console.log('Current Environment: Development Mode')
  </script>
<% } %>

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.