阿里云主机折上折
  • 微信号
Current Site:Index > Project initialization and template selection

Project initialization and template selection

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

Project Configuration and Basic Usage

Vite.js is a modern front-end build tool that leverages native browser ES module support to enable fast development server startup and hot updates. Compared to traditional bundling tools, Vite in the development environment requires almost no waiting for the bundling process, directly compiling source files on demand, significantly improving the development experience. In the production environment, it uses Rollup for efficient bundling.

Project Initialization and Template Selection

Creating a new project with Vite is very simple, and the official provides multiple methods. The most common way is to initialize the project via npm or yarn:

npm create vite@latest
# or
yarn create vite

After executing the command, you will enter an interactive command-line interface where you need to sequentially select the project name, framework, and variant. Vite supports multiple mainstream front-end frameworks:

  1. Vanilla - Pure JavaScript/TypeScript project
  2. Vue - Supports Vue 2 and Vue 3
  3. React - Supports React and React + TypeScript
  4. Preact - Lightweight React alternative
  5. Lit - Web Components framework
  6. Svelte - Compiled front-end framework
  7. Solid - Reactive JavaScript library

For example, to create a Vue 3 + TypeScript project:

npm create vite@latest my-vue-app --template vue-ts

After creation, the project directory structure typically looks like this:

my-vue-app/
├── node_modules/
├── public/
├── src/
│   ├── assets/
│   ├── components/
│   ├── App.vue
│   ├── main.ts
│   ├── style.css
│   └── vite-env.d.ts
├── index.html
├── package.json
├── tsconfig.json
└── vite.config.ts

Configuration File Details

The core configuration file for Vite is vite.config.ts (or .js), which exports a configuration object. A basic configuration example is as follows:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  server: {
    port: 3000,
    open: true
  },
  build: {
    outDir: 'dist',
    assetsDir: 'assets'
  }
})

Common configuration items include:

  • plugins: Configure the Vite plugins to use
  • server: Development server options
    • port: Specify the port number
    • open: Whether to automatically open the browser
    • proxy: Configure proxies
  • build: Production build options
    • outDir: Output directory
    • assetsDir: Static assets directory
    • minify: Whether to minify the code

Development Server and Hot Updates

Starting the development server is very simple:

npm run dev
# or
yarn dev

Vite's development server has the following features:

  1. Instant Startup - No need to wait for bundling; it is almost immediate
  2. On-Demand Compilation - Only compiles the modules needed for the current page
  3. Hot Module Replacement (HMR) - Updates modules while preserving the application state

For example, when modifying a Vue component, only that component will be reloaded without refreshing the entire page.

Environment Variables and Modes

Vite uses dotenv to load environment variables from .env files. The following files can be created in the project root directory:

  • .env: Loaded in all cases
  • .env.local: Local overrides, ignored by git
  • .env.[mode]: Environment variables for specific modes
  • .env.[mode].local: Local overrides for specific modes

Variable names must start with VITE_ to be accessible on the client side:

VITE_API_URL=https://api.example.com
VITE_DEBUG=true

In the code, they can be accessed via import.meta.env:

console.log(import.meta.env.VITE_API_URL)

Static Asset Handling

Vite provides multiple ways to handle static assets:

  1. Direct Import - Returns the resolved URL
import imgUrl from './img.png'
document.getElementById('hero-img').src = imgUrl
  1. Public Directory - Files under public are directly copied to the root directory

  2. JSON Import - JSON files can be directly imported

import pkg from './package.json'
  1. Glob Import - Batch import modules
const modules = import.meta.glob('./dir/*.js')

CSS and Preprocessor Support

Vite has built-in support for CSS and various CSS preprocessors, requiring no additional configuration:

// Directly import CSS
import './style.css'

// Import Sass
import './style.scss'

// Import Less
import './style.less'

Supports CSS Modules by adding .module to the filename:

import styles from './module.module.css'

function Component() {
  return <div className={styles.error}>Error Message</div>
}

Build Optimization

Vite automatically performs multiple optimizations during production builds:

  1. Code Splitting - Automatically splits code chunks
  2. Async Loading - Dynamically imported modules are split into separate chunks
  3. Asset Inlining - Small files are automatically converted to base64
  4. Preload Directives - Automatically generates <link rel="modulepreload">

Further optimizations can be configured:

build: {
  rollupOptions: {
    output: {
      manualChunks: {
        'vendor': ['vue', 'vue-router', 'pinia']
      }
    }
  }
}

Plugin System

Vite's plugin system is compatible with Rollup plugins and has its own unique hooks. Common official plugins include:

  • @vitejs/plugin-vue: Vue support
  • @vitejs/plugin-react: React support
  • @vitejs/plugin-legacy: Legacy browser support

Example of installing and using plugins:

npm install @vitejs/plugin-vue @vitejs/plugin-legacy -D
import vue from '@vitejs/plugin-vue'
import legacy from '@vitejs/plugin-legacy'

export default defineConfig({
  plugins: [
    vue(),
    legacy({
      targets: ['defaults', 'not IE 11']
    })
  ]
})

TypeScript Integration

Vite natively supports TypeScript without additional configuration. However, for a better development experience, you can:

  1. Configure path aliases in tsconfig.json:
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}
  1. Synchronize the configuration in vite.config.ts:
import { resolve } from 'path'

export default defineConfig({
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  }
})
  1. Create vite-env.d.ts to enhance type hints:
/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_API_URL: string
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}

Multi-Page Application Configuration

Vite supports multi-page applications by configuring multiple entries in vite.config.ts:

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')
      }
    }
  }
})

Corresponding project structure:

project/
├── about.html
├── contact.html
├── index.html
└── src/
    ├── about/
    ├── contact/
    └── main/

Custom Middleware

Custom middleware can be implemented by configuring server.middlewareMode and server.proxy:

export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        rewrite: path => path.replace(/^\/api/, '')
      }
    }
  }
})

Or directly add custom middleware:

export default defineConfig({
  server: {
    middlewareMode: true,
    configureServer(server) {
      server.middlewares.use((req, res, next) => {
        if (req.url === '/custom') {
          res.end('Hello from custom middleware')
        } else {
          next()
        }
      })
    }
  }
})

Performance Optimization Practices

  1. Dependency Pre-Building - Vite automatically pre-builds dependencies, but you can also manually configure them:
optimizeDeps: {
  include: ['vue', 'vue-router', 'lodash-es'],
  exclude: ['some-pkg']
}
  1. Use Modern Browser Features - Configure build targets:
build: {
  target: 'esnext'
}
  1. Enable gzip/brotli Compression - Use plugins:
npm install vite-plugin-compression -D
import viteCompression from 'vite-plugin-compression'

export default defineConfig({
  plugins: [
    viteCompression()
  ]
})

Test Integration

Vite can easily integrate with various testing frameworks. Using Vitest as an example:

  1. Install dependencies:
npm install vitest happy-dom @testing-library/vue -D
  1. Configure vite.config.ts:
/// <reference types="vitest" />

export default defineConfig({
  test: {
    globals: true,
    environment: 'happy-dom'
  }
})
  1. Add test scripts to package.json:
{
  "scripts": {
    "test": "vitest"
  }
}
  1. Write test files:
import { render } from '@testing-library/vue'
import MyComponent from './MyComponent.vue'

test('renders correctly', () => {
  const { getByText } = render(MyComponent, {
    props: { msg: 'Hello' }
  })
  getByText('Hello')
})

Deployment Strategies

Deploying a Vite application is very simple, mainly considering the following points:

  1. Static File Deployment - Directly deploy the dist directory after building
  2. SPA Deployment - Configure the server to redirect to index.html
  3. SSR Deployment - Requires a Node.js server environment

For static deployment, the build command is:

npm run build

The generated dist directory structure:

dist/
├── assets/
│   ├── index.[hash].js
│   └── style.[hash].css
└── index.html

Example Nginx configuration:

server {
  listen 80;
  server_name example.com;
  root /path/to/dist;
  index index.html;

  location / {
    try_files $uri $uri/ /index.html;
  }
}

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

如果侵犯了你的权益请来信告知我们删除。邮箱: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 ☕.