// vite.config.js
import { defineConfig } from 'vite';
export default defineConfig({
optimizeDeps: {
// 配置需要预构建的依赖
include: ['react', 'react-dom', 'lodash'],
// 使用esbuild进行依赖预构建
esbuildOptions: {
target: 'esnext'
}
}
});
创建Vite项目
npm init vite@latest my-vite-app -- --template react
cd my-vite-app
npm install
创建Webpack项目
npx create-react-app my-webpack-app
cd my-webpack-app
Vite启动
npm run dev
# 首次启动时间通常在500ms-1s之间
# 后续启动时间通常在100ms以内(依赖缓存)
Webpack启动
npm start
# 首次启动时间通常在3s-10s之间
# 修改文件后的热更新时间通常在500ms-2s之间
项目指标 | Vite (ms) | Webpack (ms) | 提升比例 |
---|---|---|---|
首次启动时间 | 680 | 4200 | 83.8% |
修改后热更新时间 | 85 | 1200 | 93% |
依赖预构建时间 | 1200 | 8500 | 85.9% |
// vite.config.js
export default defineConfig({
optimizeDeps: {
// 排除不需要预构建的依赖
exclude: ['some-lightweight-package'],
// 强制预构建某些依赖
include: ['@some-heavy-dependency']
}
});
// vite.config.js
export default defineConfig({
cacheDir: 'node_modules/.vite-cache', // 指定缓存目录
server: {
hmr: {
overlay: false // 禁用错误覆盖层,提高HMR性能
}
}
});
vite-plugin-eslint
npm install --save-dev vite-plugin-eslint
// vite.config.js
import eslintPlugin from 'vite-plugin-eslint';
export default defineConfig({
plugins: [eslintPlugin()]
});
vite-plugin-pwa
npm install --save-dev vite-plugin-pwa
// vite.config.js
import { VitePWA } from 'vite-plugin-pwa';
export default defineConfig({
plugins: [
VitePWA({
registerType: 'autoUpdate',
workbox: {
globPatterns: ['**/*.{js,css,html,png,jpg}']
}
})
]
});
// webpack.config.js
module.exports = {
// 开启缓存
cache: {
type: 'filesystem',
cacheDirectory: path.resolve(__dirname, '.webpack_cache')
},
// 使用thread-loader多线程处理
module: {
rules: [
{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
use: [
'thread-loader',
'babel-loader'
]
}
]
}
};
npm install --save-dev webpack-parallel-uglify-plugin
// webpack.config.js
const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin');
module.exports = {
plugins: [
new ParallelUglifyPlugin({
uglifyES: {
output: {
beautify: false,
comments: false
},
compress: {
warnings: false,
drop_console: true,
collapse_vars: true,
reduce_vars: true
}
}
})
]
};
Vite之所以比Webpack启动快,主要得益于以下几点:
对于大多数现代前端项目,尤其是开发环境,Vite是更好的选择。而Webpack在复杂项目的生产环境优化方面仍具有优势。根据项目特点选择合适的构建工具,可以显著提升开发体验和项目性能。