optional-locale-chunk-plugin.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /* eslint-env node */
  2. /* eslint import/no-nodejs-modules:0 */
  3. /**
  4. * When our locales are codesplit into cache groups, webpack expects that all
  5. * chunks *must* be loaded before the main entrypoint can be executed. However,
  6. * since we will only be using one locale at a time we do not want to load all
  7. * locale chunks, just the one the user has enabled.
  8. *
  9. * This plugin removes the locale chunks from the app entrypoint's immediate
  10. * chunk dependants list, ensuring that the compiled entrypoint will execute
  11. * *without* all locale chunks loaded.
  12. *
  13. * Note that the locale actually gets initially loaded in the server template and
  14. * the frontend code (in `app/translations`) may be redundant.
  15. */
  16. const PLUGIN_NAME = 'OptionalLocaleChunkPlugin';
  17. const clearLocaleChunks = chunks => {
  18. Array.from(chunks)
  19. .filter(chunk => chunk.name !== 'app')
  20. .forEach(chunk => {
  21. const mainGroup = Array.from(chunk.groupsIterable)[0];
  22. // With the upgrade from webpack4 -> 5, we have a lot more chunks without a name
  23. // Not entirely sure why, but we want to keep these chunks without names
  24. mainGroup.chunks = mainGroup.chunks.filter(
  25. c => !c.name || !c.name.startsWith('locale')
  26. );
  27. });
  28. };
  29. class OptionalLocaleChunkPlugin {
  30. apply(compiler) {
  31. compiler.hooks.compilation.tap(PLUGIN_NAME, compilation =>
  32. compilation.hooks.afterOptimizeChunks.tap(PLUGIN_NAME, clearLocaleChunks)
  33. );
  34. }
  35. }
  36. module.exports = OptionalLocaleChunkPlugin;