最近实习的项目需求上要求不多,就学了下项目优化,主要是首屏加载太慢。
大文件定位
我们可以使用webpack可视化插件Webpack Bundle Analyzer
查看工程js文件大小,然后有目的的解决过大的js文件。
安装
npm install --save-dev webpack-bundle-analyzer
在webpack中设置如下,然后npm run dev
的时候默认会在8888端口显示。
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; module.exports = { plugins: [ new BundleAnalyzerPlugin() ] }
JS文件按需加载
如果没有这个设置,项目首屏加载时会加载整个网站所有的JS文件,所以将JS文件拆开,点击某个页面时再加载该页面的JS是一个很好的优化方法。
这里用到的就是vue的组件懒加载。在router.js中,不要使用import的方法引入组件,使用require.ensure。
import index from '@/components/index' const index = r => require.ensure( [], () => r (require('@/components/index'),'index')) //如果写了第二个参数,就打包到该`/JS/index` 的文件中。 //不写第二个参数,就直接打包在`/JS` 目录下。 const index = r => require.ensure( [], () => r (require('@/components/index')))
使用cdn
打包时,把vue、vuex、vue-router、axios等,换用国内的bootcdn 直接引入到根目录的index.html中。
在webpack设置中添加externals,忽略不需要打包的库。
externals: { 'vue': 'Vue', 'vue-router': 'VueRouter', 'vuex': 'Vuex', 'axios': 'axios' }
在index.html中使用cdn引入。
<script src="/UploadFiles/2021-04-02/vue.min.js">将JS文件放在body的最后
默认情况下,build后的index.html中,js的引入是在header中。
使用html-webpack-plugin插件,将inject的值改成body。就可以将js引入放到body最后。
var HtmlWebpackPlugin = require('html-webpack-plugin'); new HtmlWebpackPlugin({ inject: 'body', })压缩代码并移除console
使用UglifyJsPlugin 插件来压缩代码和移除console。
new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, drop_console: true, pure_funcs: ['console.log'] }, sourceMap: false })暂时只查到了这几个优化方法。
最新资源
- 李恕权.2003-回·20年全精选2CD【SONY】【WAV+CU
- 赞多《序章》[FLAC/分轨][129.13MB]
- 群星《完美的她 影视原声带》[320K/MP3][51.98M
- 群星《完美的她 影视原声带》[FLAC/分轨][141.0
- 山风点伙.1997-深藏不露【立得】【WAV+CUE】
- 李幸倪.2018-First.Of.All.Live.Concert.3CD(20
- 李恕权.2003-回·20年全精选2CD【SONY】【WAV+CU
- 群星《你就在我身边 电影原声专辑》[320K/MP3][
- 群星《你就在我身边 电影原声专辑》[FLAC/分轨]
- 班得瑞原装进口《20周年精选集》1CD[APE/CUE分轨