前端工程化:Vite与Rollup构建优化

前端工程化:Vite与Rollup构建优化

大家好,我是欧阳瑞(Rich Own)。今天想和大家聊聊前端工程化这个重要话题。作为一个全栈开发者,构建工具是日常开发中不可或缺的一部分。今天就来分享一下Vite和Rollup的构建优化技巧。

为什么需要构建优化?

问题 说明
构建速度慢 影响开发效率
包体积大 影响加载速度
资源重复 增加不必要的网络请求
缓存失效 导致用户重复下载

Vite入门

配置Vite

javascript 复制代码
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  build: {
    outDir: 'dist',
    sourcemap: false,
    minify: 'terser'
  }
});

优化配置

javascript 复制代码
export default defineConfig({
  plugins: [react()],
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
          lodash: ['lodash']
        }
      }
    },
    chunkSizeWarningLimit: 500
  }
});

Rollup进阶

代码分割

javascript 复制代码
// rollup.config.js
import { terser } from 'rollup-plugin-terser';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';

export default {
  input: 'src/index.js',
  output: {
    dir: 'dist',
    format: 'es',
    sourcemap: false
  },
  plugins: [resolve(), commonjs(), terser()],
  external: ['react', 'react-dom']
};

树摇优化

javascript 复制代码
// package.json
{
  "sideEffects": false
}

实战案例

构建分析

bash 复制代码
npm install rollup-plugin-visualizer --save-dev
javascript 复制代码
// vite.config.js
import { visualizer } from 'rollup-plugin-visualizer';

export default defineConfig({
  plugins: [react(), visualizer()]
});

路径别名

javascript 复制代码
// vite.config.js
import path from 'path';

export default defineConfig({
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  }
});

最佳实践

1. 按需加载

javascript 复制代码
const HeavyComponent = lazy(() => import('./HeavyComponent'));

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <HeavyComponent />
    </Suspense>
  );
}

2. 图片优化

javascript 复制代码
// vite.config.js
import viteImagemin from 'vite-plugin-imagemin';

export default defineConfig({
  plugins: [viteImagemin()]
});

3. 环境变量

javascript 复制代码
// .env
VITE_APP_API_URL=https://api.example.com
javascript 复制代码
// src/api.js
const apiUrl = import.meta.env.VITE_APP_API_URL;

总结

前端工程化是提高开发效率和应用性能的关键。通过合理配置Vite和Rollup,可以显著优化构建流程和产物质量。

我的鬃狮蜥Hash对构建优化也有自己的理解------它总是用最有效的方式捕捉蟋蟀,这也许就是自然界的"构建优化"吧!

如果你对前端工程化有任何问题,欢迎留言交流!我是欧阳瑞,极客之路,永无止境!


技术栈:Vite · Rollup · 前端工程化

相关推荐
Richown5 小时前
数据分析:Pandas与数据清洗实战
区块链·react
Richown6 小时前
Web3钱包开发:使用Ethers.js集成MetaMask
区块链·react
Richown6 小时前
机器学习入门:TensorFlow.js实战
区块链·react
mutourend20 小时前
Zcash 与量子计算机
区块链·量子计算·后量子密码学
TechubNews1 天前
稳定币下一战:不是谁发币,而是谁掌握结算通道
人工智能·web3·区块链
mutourend1 天前
量子计算与区块链:让紧迫性与真实威胁相匹配
区块链·量子计算·后量子密码学
多年小白1 天前
A股算力租赁板块 深度分析
大数据·人工智能·ai·金融·区块链
架构源启1 天前
Spring AI 进阶系列- Agent 智能体开发:ReAct模式、多步推理与自主Agent实战
人工智能·spring·react·ai agent·智能体·springai
小牛itbull1 天前
ReactPress 3.0 :一分钟拥有自己的 CMS & 博客
开源·cms·react·博客系统·reactpress