Tree Shaking 为什么没把第三方库的无用代码去掉?

司空若曦 阅读 63

我用 Vite + Vue3 开发,引入了 lodash-es,但打包后发现整个库都被打进去了,明明只用了 debounce 啊?

我已经按文档写了 import { debounce } from ‘lodash-es’,也确认 vite.config.js 里没关掉 tree shaking,但 bundle 分析显示 lodash-es 全量引入。是不是我哪里配置错了?

<script setup>
import { debounce } from 'lodash-es'

const handleInput = debounce(() => {
  console.log('input changed')
}, 300)
</script>

<template>
  <input @input="handleInput" />
</template>
我来解答 赞 13 收藏
二维码
手机扫码查看
2 条解答
培聪的笔记
改成这样试试:
import debounce from 'lodash-es/debounce'
这样直接按路径引入具体方法,Tree Shaking 才能生效。有时候打包器对这种库的处理就是有点迷,直接指定路径最保险。
点赞
2026-03-29 20:16
司空新霞
lodash-es 需要这样引入:import debounce from 'lodash-es/debounce',用路径引入具体模块就行了。

要么在 vite.config.js 加这个:

optimizeDeps: {
include: ['lodash-es/debounce']
}
点赞
2026-03-07 19:01