目录
cdn加速
市面主流cdn价格比较
最终选择了腾讯云,因为可以免费送6个月,哈哈哈
- 在域名管理中添加域名,一定是要备案了的
- 将生成给你的cname值在你的DNS管理处进行配置,如果cdn访问域名和cname相同,则可不用A记录类型了,直接用CNAME记录类型替代即可
- 生效后截图
首页服务端渲染
提出公共依赖
- 将vue,vuex,axios,js-cookie,vue-lazyload,vue-router,pk-view,view-design等放入vue.config.js的externals中
注意scripts方式引用依赖时依赖所暴露出的变量名,如pk-view为pkView,view-design为iview,不然会在项目中找不到
if (process.env.NODE_ENV === 'production') {
config.externals = cdn.externals
}
- 在index.html中加入对应的依赖js,由于自身服务器已经cdn加速了,所以直接放在本地即可
- 通过html插件注入cdn配置并在index.html中引用
if (process.env.NODE_ENV === 'production') {
config.plugin('html').tap(args => {
// 生产环境或本地需要cdn时,才注入cdn
args[0].cdn = cdn
return args
})
}
<% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.js) { %>
<script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script>
<% } %>
图片压缩(tinyimg-webpack-plugin)
两个选择:
- image-webpack-loader(在arm64平台编译报错,所以没用,首推还是这个)
- tinyimg-webpack-plugin(仿tinyimg接口写的一个免费插件)
图片懒加载(v-lazyload)
使用依赖vue-lazyload
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
preLoad: 1.3,
error: require('@/assets/images/common/error.svg'),
loading: require('@/assets/images/common/loading.svg'),
attempt: 1
})
webpack配置,修改cachegroup,改变首页引入的js大小
部分页面使用了tui-editor,但是首页并没有,所以必须要将其单独抽离成一个js文件,不在入口文件处加载,在test方法中将与此包有关的依赖都放进去
config.optimization = {
// 代码分离
runtimeChunk: {
name: entrypoint => `runtime~${entrypoint.name}`
},
splitChunks: {
cacheGroups: {
vendor: {
name: 'vendor',
minChunks: 2,
reuseExistingChunk: true,
priority: 20,
minSize: 300000,
chunks: 'all',
test: /[\\/]node_modules[\\/]/
},
common: {
name: 'common',
minChunks: 2,
reuseExistingChunk: true,
priority: 10,
minSize: 30000,
chunks: 'all',
test: /[\\/]src[\\/]/,
},
markdown: {
name: 'markdown',
minChunks: 1,
priority: 30,
minSize: 0,
chunks: 'all',
// test: /[\\/]node_modules[\\/]pk-markdown[\\/]/
test(module) {
// `module.resource` contains the absolute path of the file on disk.
// Note the usage of `path.sep` instead of / or \, for cross-platform compatibility.
const editorList = ['tui', 'highlight', 'codemirror', 'markdown-it', 'plantuml-encoder', 'to-mark', '@types/codemirror', '@types/jquery', '@types/markdown-it', 'resize-observer-polyfill', 'squire-rte']
return editorList.some(v => {
return module.resource && module.resource.includes(`${path.sep}node_modules${path.sep}${v}`)
})
},
}
}
},
minimizer: [
new TerserPlugin({
sourceMap: true, // Must be set to true if using source-maps in production
terserOptions: {
compress: {
drop_console: true,
},
},
}),
],
}
使用webpack-bundle-analyzer
查看效果,美滋滋
抽离iview,做按需加载
之前已经将iview做了公共依赖抽离,但有些非vue组件的地方仍引用了部分ivew功能,所以还需对用到的iview做按需加载
在babel.config.js中加入
module.exports = {
presets: [
[
'@vue/app',
{
useBuiltIns: 'entry'
}
]
],
'plugins': process.env.NODE_ENV === 'production' ? [['import', {
'libraryName': 'view-design',
'libraryDirectory': 'src/components'
}]] : []
}
首页白屏添加等待条
在public文件夹中放入一个loading.gif的图片,然后在App.vue的created生命周期中将其删除,可以缓解网速较慢情况下首页加载白屏时间过长的尴尬