You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NuxtJS项目中date-fns 2.27.0 tree-shaking不生效如何解决?

Nuxt项目date-fns tree-shaking失效解决方案

1. 修正locale导入方式

默认从date-fns/locale批量导入会引入全量语言包,需改为单个locale单独导入:

// 错误写法,会打包所有locale
// import { fr } from 'date-fns/locale';
// 正确写法,仅引入法语locale
import fr from 'date-fns/locale/fr'

2. 避免Babel将date-fns转为CommonJS模块

webpack的tree-shaking仅支持ES模块,若Babel将date-fns的ES模块转译为CommonJS,会导致tree-shaking失效。在nuxt.config.js中添加如下配置:

export default {
  build: {
    babel: {
      exclude: [/node_modules\/date-fns/],
      presets({ isServer }, [preset, options]) {
        // 关闭ES模块转CommonJS的配置
        options.modules = false
      }
    }
  }
}

3. 降级为单函数导入(兜底方案)

若上述配置仍不生效,可直接按路径导入单个函数,该写法无需依赖tree-shaking即可保证仅打包用到的代码:

// 替换原有批量导入写法
import parseISO from 'date-fns/parseISO'
import formatDistanceToNow from 'date-fns/formatDistanceToNow'

4. 额外校验项

  • 执行npm ls date-fns或yarn why date-fns排查是否存在第三方依赖全量引入date-fns,或项目中存在多个版本date-fns的情况
  • 手动开启webpack优化配置,在nuxt.config.js中添加:
export default {
  build: {
    extend(config, { isDev, isClient }) {
      if (!isDev && isClient) {
        config.optimization.usedExports = true
        config.optimization.sideEffects = true
      }
    }
  }
}

配置完成后重新打包,正常情况下date-fns打包后Gzip体积可降至5KB以内。

内容的提问来源于stack exchange,提问作者Guillaume Prévost

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 01:57:02