• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

vue-i18n报错You are running the esm-bundler build of vue-i18n的解决方案

武飞扬头像
Ricky__H
帮助1

最近在Vue3 TS Vite的项目开发中,使用vue-i8n遇到警告:

You are running the esm-bundler build of vue-i18n. It is recommended to configure your bundler to explicitly replace feature flag globals with boolean literals to get proper tree-shaking in the final bundle.

 查看vue-i18n文档,找到这样的说明:

For Bundler feature flags

Build Feature Flags

The esm-bundler builds now exposes global feature flags that can be overwritten at compile time:

  • __VUE_I18N_FULL_INSTALL__ (enable/disable, in addition to vue-i18n APIs, components and directives all fully support installation: true)
  • __VUE_I18N_LEGACY_API__ (enable/disable vue-i18n legacy style APIs support, default: true)
  • __INTLIFY_PROD_DEVTOOLS__ (enable/disable @intlify/devtools support in production, default: false)

NOTE: __INTLIFY_PROD_DEVTOOLS__ flag is experimental, and @intlify/devtools is WIP yet.

The build will work without configuring these flags, however it is strongly recommended to properly configure them in order to get proper tree shaking in the final bundle. To configure these flags:

Note: the replacement value must be boolean literals and cannot be strings, otherwise the bundler/minifier will not be able to properly evaluate the conditions.

大体意思就是在使用包管理器的项目,如webpack、rollup、vite之类工具,需要配置vue-i18n的全局变量,以便在dev环境可以获得良好的提示,而在prod环境丢掉对于生产无用的代码以及按需引入得到tree shaking的效果。

那么,如何配置呢?我是vite项目,在vite官方找到这样的说明:

define

  • 类型: Record<string, any>

定义全局常量替换方式。其中每项在开发环境下会被定义在全局,而在构建时被静态替换。

  • String 值会以原始表达式形式使用,所以如果定义了一个字符串常量,它需要被显式地打引号。(例如使用 JSON.stringify

  • 为了与 esbuild 的行为保持一致,表达式必须为一个 JSON 对象(null、boolean、number、string、数组或对象),亦或是一个单独的标识符。

  • 替换只会在匹配到周围不是其他字母、数字、_ 或 $ 时执行。

WARNING

因为它是不经过任何语法分析,直接替换文本实现的,所以我们建议只对 CONSTANTS 使用 define

例如,process.env.FOO 和 __APP_VERSION__ 就非常适合。但 process 或 global 不应使用此选项。变量相关应使用 shim 或 polyfill 代替。

NOTE

对于使用 TypeScript 的开发者来说,请确保在 env.d.ts 或 vite-env.d.ts 文件中添加类型声明,以获得类型检查以及代码提示。

示例:

ts

  1.  
    // vite-env.d.ts
  2.  
    declare const __APP_VERSION__: string

NOTE

由于开发模式和构建模式实现 define 的差异性,我们应该避免采用一些可能导致不一致的用例。

例如:

js

  1.  
    const obj = {
  2.  
    __NAME__, // 不要以缩写形式定义对象属性
  3.  
    __KEY__: value // 不要定义对象的 key
  4.  
    }

简而言之,就是在项目vite.config.ts中进行如下配置:

  1.  
     export default defineConfig({
  2.  
     
  3.  
          define: {__VUE_I18N_FULL_INSTALL__: true, __VUE_I18N_LEGACY_API__: true, __INTLIFY_PROD_DEVTOOLS__: false},
  4.  
     
  5.  
    })

如果有类型检查报错,就像上面说的在 env.d.ts 添加类型说明:

  1.  
    // vite-env.d.ts
  2.  
    declare const __APP_VERSION__: string

至此,问题解决,不会有警告,而且推荐的功能也全用上了。 

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhhkbgfb
系列文章
更多 icon
同类精品
更多 icon
继续加载