[Vie] 依赖预构建

使用Vite模板vue-ts. https://github.com/vitejs/vite/tree/main/packages/create-vite

 

 

一个组件在没加入Lodash之前:

当加入lodash之后,会自动把它加入到.vite/deps中去:

 

假如不用依赖构建

vite.config.ts

  return {
    plugins: [vue()],
    // ...
    optimizeDeps: {
      exclude: ['lodash-es']
    }
  }

可以看到,lodash已经从.vite/deps中被移除了

在网页加载的时候形成了瀑布流问题。

 

利用esbuild来简单的实现

pnpm add esbuild -D

prebundle.cjs

const esbuild = require('esbuild');

//用户存放扫描到的第三方依赖包的名称
const deps = [];

//扫描插件
function depScanPlugin(deps) { 
  return {
    name: 'esbuild-dep-scan',
    setup(build) { 
      // 正则表达式,简单判断所有不以.开头的路径都是第三方依赖
      build.onResolve({ filter: /^[^\.]/ }, args => {
        // 将扫描到的第三方依赖包名称存入deps数组中
        deps.push(args.path);
      })
    }
  }
}
//进行依赖扫描
(async () => {
  await esbuild.build({
    // 依赖预构建扫描不需要写入文件
    write: false,
    entryPoints: ['src/index.js'],
    //是否需要打包
    bundle: true,
    outdir: './dist',
    loader: {
      '.js': 'jsx',
      '.svg': 'dataurl',
      '.png': 'file'
    },
    plugins: [depScanPlugin(deps)]
  });


  await esbuild.build({
    // 入口文件就是上面扫描的地址
    entryPoints: deps,
    write: true,
    bundle: true,
    format: 'esm', 
    outdir:'./node_modules/.vite/deps',
  })
})();
  • 先扫描文件,把所有第三方库加到deps数组中去
  • 然后写入到把第三方库的bundle写入到'./node_modules/.vite/deps'中
posted @   Zhentiw  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2024-02-06 [Go] Unit testing Go code
2024-02-06 [Go] Go routines with WaitGroup and async call
2024-02-06 [ Go] GoRoutines and Channels
2024-02-06 [Go - slice] Remove Elements from a slice in Go
2024-02-06 [Go] defer & recover
2024-02-06 [Go] Defer keyword
2023-02-06 [Typescript] Global Scope
点击右上角即可分享
微信分享提示