UNPKG

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