'webpack creating 100's of js chunks crippling performance for a single page view with vue cli

We have a vuejs 2 project.

We needed some function of dayjs.

We abstracted the dayjs into a single utility file and following the guide ended up with this:

import { i18n } from '@/plugins/i18n';
import dayjs from 'dayjs';
import calendar from 'dayjs/plugin/calendar';

dayjs.extend(calendar);

export default async (date: Date, locale?: string): Promise<string> => {
  import(`dayjs\locales\${locale}`)
  const time:any = i18n.t('datetime.dict');
  return dayjs(date).locale(userLocale).calendar(null, {
      lastDay: `[${time.yesterday} ${time.at}] LT`,
      sameDay: `[${time.today} ${time.at}] LT`,
      nextDay: `[${time.tomorrow} ${time.at}] LT`,
      lastWeek: `[${time.last}] dddd [${time.at}] LT`,
      nextWeek: `dddd [${time.at}] LT`,
      sameElse: 'LLLL'
  });
};

The app works perfectly fine, but vuejs is outputting every single langauge file from dayjs as a chunk and also adding the prefetch script tag to the index.html.

Has anyone else hit this issue and is the above code snippet wrong or should there be a more precise import?

Here is a screenshot of only some of the dayjs chunks.. each is completely the same with different langauge strings in... but we didn't even import the locale setting options yet. enter image description here



Solution 1:[1]

@MichalLevĂ˝ gave the direction to the answer to this issue.

Essentially, webpack cannot know which single file to import when you say:

 import(`dayjs\locales\${locale}`)

So.. it just creates a js chunk for every single file it finds. Which is not overly bad on its own.

When you combine this behaviour with vue-cli's default prefetch behaviour, this is when things get bad... the result is that every single chunk that webpack creates ends up being a "pre-fetched" line in the HTML head in the outputted index HTML file.

So when there is 400 chunks from a dynamic import (in this case locales from dayjs) then there is a prefetch for all of them.

It depends on your setup but.. for us, the app is also a PWA so there is effectively no requirement for prefetching as the PWA will also download... in fact it doubles the downloads.

The answer for us was to be more specific on the prefetch: https://cli.vuejs.org/guide/html-and-static-assets.html#prefetch

And also, as we only needed a few languages, import only what was needed but being specific and not passing a variable to map to a path

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1