jmblog/how-to-optimize-momentjs-with-webpack
关于
讲解如何使用 webpack 优化 moment.js 庞大的打包体积
其他项目实测星标增长
- 24小时
- 0
- 7天
- -1
- 15天
- -2
- 1个月
- 正在收集历史
各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。
README.md
原文How to optimize moment.js with webpack
When you write var moment = require('moment') in your code and pack with webpack, the size of the bundle file gets heavyweight because it includes all locale files.

To optimize the size, the two webpack plugins are available:
IgnorePluginContextReplacementPlugin
Using IgnorePlugin
You can remove all locale files with the IgnorePlugin.
const webpack = require('webpack');
module.exports = {
//...
plugins: [
// Ignore all locale files of moment.js
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
};
And you can still load some locales in your code.
const moment = require('moment');
require('moment/locale/ja');
moment.locale('ja');
...
Create React App and Next.js use this solution.
Using ContextReplacementPlugin
If you want to specify the including locale files in the webpack config file, you can use ContextReplacementPlugin.
const webpack = require('webpack');
module.exports = {
//...
plugins: [
// load `moment/locale/ja.js` and `moment/locale/it.js`
new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /ja|it/),
],
};
In this case, you don't need load the locale files in your code.
const moment = require('moment');
moment.locale('ja');
...
Measurements
- webpack: v3.10.0
- moment.js: v2.20.1
| File size | Gzipped | |
|---|---|---|
| Default | 266 kB | 69 kB |
| w/ IgnorePlugin | 68.1 kB | 22.6 kB |
| w/ ContextReplacementPlugin | 68.3 kB | 22.6 kB |
Alternatives
If you are looking for the alternatives to moment.js, please see https://github.com/you-dont-need/You-Dont-Need-Momentjs.
References
探索相关项目
加载中…