alienfast / vite-plugin-i18next-loader

Vite plugin to client bundle i18next locales composited from one to many json/yaml files from one to many libraries. Zero config HMR support included.
Other
41 stars 4 forks source link

Chunking/tree shaking via lang-based named imports #4

Open rosskevin opened 2 years ago

rosskevin commented 2 years ago

Since the output of the plugin is an ESM export, perhaps it makes sense for us to enumerate langs and export them independently at the top, in addition to one default export (which includes all langs for those that don't care).

I suspect that a named dynamic import would then be tree-shakeable. I could be wrong, but interested in other's thoughts.

rosskevin commented 2 years ago

Named exports were added as part of #3. Need to try dynamic import as well as update docs if it works.

rosskevin commented 2 years ago

I added this to the readme - one idea is to look into how vite supports tree shaking of json, and perhaps export as json itself instead of using named exports?

https://vitejs.dev/guide/features.html#json


Note that the virtual module generated has contents that conform to the i18next resource format.

While using the output with import resources from 'virtual:i18next-loader' will not be tree-shaken, it is possible to use the named outputs with a dynamic import for tree shaking/chunking optimizations. If you take advantage of this, please see #4 and take a moment to update this doc with more information.

NOTE as shown by the test output below, due to ES syntactical rules, we cannot use hyphenated lang codes. I'm open to ideas, but in the interim, affected lang codes are exported with the hyphen converted to underscore e.g. zh-cn has a named export of zh_cn. I noted that vite allows for tree-shaking of JSON files, perhaps that is worth looking at to consider how it might help us and inform our output?

export const en = {
  foo: { test: 'app foo.test en' },
  main: {
    test: 'app test en',
    sub: {
      slug: 'app sub.slug en',
      test: 'lib sub.test en',
      subsub: { slugslug: 'app sub.subsub.slugsub en', test: 'lib sub.subsub.test en' },
    },
  },
}
export const zh_cn = {
  foo: { test: 'app foo.test zh-cn' },
  main: {
    test: 'app test zh-cn',
    sub: {
      slug: 'app sub.slug zh-cn',
      test: 'lib sub.test zh-cn',
      subsub: { slugslug: 'app sub.subsub.slugsub zh-cn', test: 'lib sub.subsub.test zh-cn' },
    },
  },
}
const resources = {
  en,
  'zh-cn': zh_cn,
}
export default resources
filipw01 commented 1 year ago

@rosskevin I don't think tree shaking will work because of this issue https://github.com/rollup/rollup/issues/2512 in rollup

veeramarni commented 8 months ago

@rosskevin any moment on this?

rosskevin commented 8 months ago

@veeramarni I have no pressing need, but I'm open to PRs.