intlify / bundle-tools

bundling for intlify i18n tools
MIT License
232 stars 37 forks source link

feat(unplugin-vue-i18n): exclude unused locales from the bundle #301

Closed imslepov closed 9 months ago

imslepov commented 9 months ago

Motivation

When developing projects, we use Nuxt Layers to reuse common components with business logic between similar projects. For one of the projects we need only English, and for the other only German. Because the bundle of both applications includes translations of both languages, the size of unused code that is loaded in the browser also increases.

Description of changes

In this PR I added a new onlyLocales property to @intlify/unplugin-vue-i18n config. By using it you can exclude from the bundle those localizations that are not specified in the plugin settings.

For example:

// vite.config.ts
export default defineConfig({
  plugins: [
    vueI18n({
      onlyLocales: ['ja']
    })
  ]
})
<template>
  <!-- App.vue -->
  <p>{{ t('hello') }}</p>
</template>

<i18n>
{
  "en": {
    "hello": "hello, world!"
  },
  "ja": {
    "hello": "こんにちは、世界!"
  }
}
</i18n>

As a result of the build, there will be no other localizations in the bundle:

// bundle.js
export default function (Component) {
  const _Component = Component
  _Component.__i18n = _Component.__i18n || []
  _Component.__i18n.push({
    "locale": "",
    "resource": {
      "ja": {
         // body
      }
      // resources for locale "en" are not provided because "en" is not specified in vite.config.ts
    }
  })
}

Tests