在使用moment.js时,由于默认的moment库会引入全部的语言资源文件,导致最后打包时体积非常大,这时我们可以通过webpack自带的插件来精简掉这些语言资源文件
使用 IgnorePlugin
以下这段代码加到webpack的config中,可以在打包时排除moment中所有的locale下的文件
const webpack = require('webpack');
module.exports = {
//...
plugins: [
// Ignore all locale files of moment.js
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
};
如果你只需要加载某些语言包,也可以在需要的时候手动引用一次
const moment = require('moment');
require('moment/locale/ja');
moment.locale('ja');
...
经查阅,IgnorePlugin 这个插件的功能是防止在 import 或 require 调用时,生成以下正则表达式匹配的模块:
- requestRegExp 匹配(test)资源请求路径的正则表达式。
- contextRegExp (可选)匹配(test)资源上下文(目录)的正则表达式。
new webpack.IgnorePlugin(requestRegExp, [contextRegExp])