Vite:下一代前端构建工具的快速指南
Vite 是 Vue.js 作者 Yuxi You 开发的新一代前端构建工具,以快速冷启动、按需编译、热更新等能力受到广泛关注。Vite 利用浏览器原生的 ES 模块导入功能,提供近乎即时的开发环境启动速度和高度优化的开发体验。
安装 Vite
首先确保你的系统中安装了 Node.js(建议使用 LTS 版本)。然后通过 npm 或 yarn 全局安装 Vite:
npm install -g create-vite # Or use yarn yarn global add create-vite
创建新项目
使用 `create-vite` 命令创建一个新的 Vite 项目。以下是创建 Vue 项目的示例:
create-vite my-vite-project --template vue cd my-vite-project
这将初始化一个基于 Vue 3 的 Vite 项目。
开发和运行
在项目根目录下,运行以下命令启动开发服务器:
npm run dev # Or use yarn yarn dev
Vite 会立即启动一个本地开发服务器,你可以在浏览器中访问 `http://localhost:5173` 查看你的应用程序。Vite 支持热模块替换(HMR),这意味着当你编辑代码时,浏览器页面会实时更新,无需刷新。
构建生产版本
当您准备好部署应用程序时,运行以下命令来构建生产版本:
npm run build # Or use yarn yarn build
这将生成一个优化的、可用于生产的静态文件夹,通常位于“dist”目录中。
Vite 配置
// vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue'; // Assume we use Vue
import { resolve } from 'path';
// Environment variables
const env = process.env.NODE_ENV === 'production' ? 'prod' : 'dev';
export default defineConfig({
// Application base path
base: '/my-app/',
// Project entry file
root: './src',
// Output directory
outDir: 'dist',
mode: env,
envPrefix: 'VITE_', // All environment variables starting with VITE_ will be injected into import.meta.env
envFile: `.env.${env}.local`, // Read the .env file for the corresponding environment
// Dynamically import polyfill
optimizeDeps: {
include: ['@vue/reactivity'], // Force inclusion of dynamically imported libraries
},
// Server configuration
server: {
// Server port
port: 3000,
// Whether to enable HTTPS
https: false,
// Enable hot module replacement
hmr: true,
// Proxy configuration for API request forwarding
proxy: {
'/api': {
target: 'http://localhost:8000',
changeOrigin: true,
},
},
middlewareMode: true, // Enable middleware mode
before(app) {
app.use(async (ctx, next) => {
ctx.body = 'Hello, this is a custom middleware!';
await next();
});
},
},
// Build configuration
build: {
// Whether to compress code in the production environment
minify: true,
// Output directory
outDir: 'dist',
// Resource file storage directory
assetsDir: 'assets',
// Chunk size warning threshold
chunkSizeWarningLimit: 500,
rollupOptions: {
input: 'src/main.js',
output: {
manualChunks(id) {
if (id.startsWith('node_modules')) {
return id.toString().replace(/(\.[a-z]+)|[\\/]/g, '_');
}
},
},
},
},
// Preprocessor configuration, such as CSS
css: {
// CSS modularization
modules: {
generateScopedName: '[name]_[local]_[hash:base64:5]',
},
},
// Preview environment configuration
preview: {
port: 8080,
},
// Plugin configuration
plugins: [
// You can add custom or third-party plugins here
],
// Resolve options
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
// Alias configuration
alias: {
'@': '/src',
},
},
// Esbuild configuration for optimizing build speed
esbuild: {
// Enable/disable esbuild tree shaking
treeShaking: true,
jsxFactory: 'h',
jsxFragment: 'Fragment',
},
transpileDependencies: ['my-dep'], // Specify dependencies to be translated
// Additional Rollup configuration
rollupOptions: {
// You can add Rollup configuration items here
},
});