Include info on how to tree shake dynamically imported locales
See original GitHub issueIf locale is required dynamically all languages in the date-fns are loaded into bundle (~160kb). However it is possible to use webpack to trim down the languages added to bundle using Context replacement plugin.
Usage example
const getLocale = (locale) => require(`date-fns/locale/${locale}/index.js`);
const formatDate = (date, formatStyle, locale) => {
return format(date, formatStyle, {
locale: getLocale(locale)
});
};
Config example:
const supportedLocales = ["en", "de", "pl", "it"]
plugins: [
new ContextReplacementPlugin(/date\-fns[\/\\]/, new RegExp(`[/\\\\\](${supportedLocales.join('|')})[/\\\\\]`)),
]
This results in a language bundle of ~23kb.
Issue Analytics
- State:
- Created 5 years ago
- Comments:9 (7 by maintainers)
Top Results From Across the Web
Tree Shaking - webpack
Tree shaking is a term commonly used in the JavaScript context for ... It relies on the static structure of ES2015 module syntax,...
Read more >Dynamically Import ESModules and Tree Shake them too!
The problem is that we cannot tree-shake dynamic imports. An explanation to this has been provided in this article. Would it not be...
Read more >How do I dynamically import locales in Angular 9?
Please make sure it is in your tsconfig via the 'files' or 'include' property. Commenting out the imports and call to registerLocaleData ...
Read more >How to Fully Optimize Webpack 4 Tree Shaking | by Craig Miller
One of our main goals was to take advantage of tree-shaking, where Webpack ... as Webpack treats library imports differently from local code ......
Read more >Dynamic Import and Tree Shaking in JavaScript | by Moon
So, require , which is common JavaScript syntax, isn't supported. For example, Webpack names every module and it includes the modules that are ......
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Tree shaking and lazy loading are different terms. Tree shaking is to exclude the unused files or scripts, I think what you are trying here is webpack code splitting, which can be done by dynamic import(from wepack v2). It will generate a separate chunk file which can be requested lazily, it’s a common use case for i18n. https://webpack.js.org/guides/code-splitting/#dynamic-imports
This feels like a webpack config tip which has nothing to do with
moment.js
ordate-fns
…I’m not sure what you want to add to the docs but if you submit a PR we can have a look!