1 | # webpack
|
2 |
|
3 | ## Removing unused languages from dynamic import
|
4 |
|
5 | If locale is required dynamically all languages in the date-fns are loaded by webpack into bundle (~160kb) or split across the chunks. This prolongs the build process and increases the amount of space taken. However, it is possible to use webpack to trim down languages using [ContextReplacementPlugin].
|
6 |
|
7 | Let's assume that we have a single point in which supported locales are present:
|
8 |
|
9 | `config.js`:
|
10 |
|
11 | ```js
|
12 | export const supportedLocales = ['en', 'de', 'pl', 'it']
|
13 | ```
|
14 |
|
15 | We could also have a function that formats the date:
|
16 |
|
17 | ```js
|
18 | const getLocale = locale => require(`date-fns/locale/${locale}/index.js`)
|
19 |
|
20 | const formatDate = (date, formatStyle, locale) => {
|
21 | return format(date, formatStyle, {
|
22 | locale: getLocale(locale)
|
23 | })
|
24 | }
|
25 | ```
|
26 |
|
27 | In order to exclude unused languages we can use webpacks [ContextReplacementPlugin].
|
28 |
|
29 | `webpack.config.js`:
|
30 |
|
31 | ```js
|
32 | import webpack from 'webpack'
|
33 | import { supportedLocales } from './config.js'
|
34 |
|
35 | export default const config = {
|
36 | plugins: [
|
37 | new webpack.ContextReplacementPlugin(
|
38 | /date\-fns[\/\\]/,
|
39 | new RegExp(`[/\\\\\](${supportedLocales.join('|')})[/\\\\\]`)
|
40 | )
|
41 | ]
|
42 | }
|
43 | ```
|
44 |
|
45 | This results in a language bundle of ~23kb .
|
46 |
|
47 | [ContextReplacementPlugin]: https://webpack.js.org/plugins/context-replacement-plugin/ |
\ | No newline at end of file |