moment默認導入,會引入全部的語言資源文件。
而我們最終使用到的語言資源僅僅是其中的一部分。
默認導入打包後文件大小情況:
我們現在的目的是精簡左邊的 locale 語言資源文件。
方案一:使用 webpack.IgnorePlugin
1. webpack.config.js
const webpack = require('webpack')
// 其他相關配置已省略
module.exports = {
plugins: [new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)]
}
或者你使用的是 Vue-cli3.0 腳手架生成的項目
在項目`vue.config.js`(沒有則新建)
const webpack = require('webpack')
module.exports = {
configureWebpack:{
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
]
}
}
打包時忽略/moment/locale/ 文件夾
然後進入你的項目入口配置 moment
import moment from 'moment'
// 你想要的語言
import 'moment/locale/zh-cn'
import 'moment/locale/ja'
moment.locale('zh-cn')
配置完成後打包:(我要什麼語言資源就打了什麼進去)
方案二:使用 webpack.ContextReplacementPlugin(推薦)
只需要配置 webpack 插件
const webpack = require('webpack')
module.exports = {
configureWebpack:{
plugins: [
new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /zh-cn|ja/)
]
}
}
配置完成後打包:(和方案一結果一樣)