最近开发了一个项目属于一个项目集。包含很多功能,并且开发的人员也很多,就造成了打包过后,在生产环境第一次加载页面就很慢。网页出现白板时间很长。用户体验性不好。所以就针对第三方引入按需加载这里做了一个说明。
1:查看加载慢的原因。vue 有插件 “webpack-bundle-analyzer”,可视化打包图形模板。能够清晰的看见,那个板块体积很大
npm install webpack-bundle-analyzer
然后在vue.config.js 引入使用
const { defineConfig } = require("@vue/cli-service");
const BundleAnalyzerPlugin =
require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave: false, //false关闭命名规范
configureWebpack: {
module: {
plugins: [new BundleAnalyzerPlugin()],
},
});
最后运行启动代码。 就会默认加载一个可视化图形。
还有很多默认配置项,想要更清楚的了解 可以自行查阅
// BundleAnalyzerPlugin 配置的具体配置项(默认)
// new BundleAnalyzerPlugin({
// analyzerMode: 'server',
// analyzerHost: '127.0.0.1',
// analyzerPort: '8888',
// reportFilename: 'report.html',
// defaultSizes: 'parsed',
// openAnalyzer: true,
// generateStatsFile: false,
// statsFilename: 'stats.json',
// statsOptions: null,
// excludeAssets: null,
// logLevel: info
// })
我这里查看是因为element UI 全局引入了,但是很多组件我都没有使用,就造成体积很大。这里我把element UI 按需引入
element 按需引入 先要
npm install babel-plugin-component
引入element 按需引入插件。
然后在你的公共JS 文件中新建一个elementUI.js
在mian.js 中引入此文件。
按需引入文件内容
/**
* 按实际使用 导出组件
*/
import Vue from "vue";
import {
Button,
Select,
Input,
Switch,
Radio,
Checkbox,
Tag,
TimePicker,
DatePicker,
Pagination,
Avatar,
Notification,
Menu,
Submenu,
MenuItem,
MenuItemGroup,
Dropdown,
Steps,
Dialog,
Tooltip,
Popover,
Card,
Carousel,
CarouselItem,
Collapse,
Timeline,
Divider,
Image,
Form,
FormItem,
Tabs,
Table,
TableColumn,
TabPane,
Tree,
Alert,
Slider,
Icon,
Upload,
Progress,
Loading,
Message,
MessageBox,
} from "element-ui";
Vue.use(Form);
Vue.use(FormItem);
Vue.use(Tabs);
Vue.use(TabPane);
Vue.use(Tree);
Vue.use(Alert);
Vue.use(Slider);
Vue.use(Icon);
Vue.use(Upload);
Vue.use(Progress);
Vue.use(Button);
Vue.use(Select);
Vue.use(Input);
Vue.use(Switch);
Vue.use(Radio);
Vue.use(Checkbox);
Vue.use(Tag);
Vue.use(Table);
Vue.use(TableColumn);
Vue.use(TimePicker);
Vue.use(DatePicker);
Vue.use(Pagination);
Vue.use(Avatar);
Vue.use(Notification);
Vue.use(Menu);
Vue.use(Submenu);
Vue.use(MenuItem);
Vue.use(MenuItemGroup);
Vue.use(Dropdown);
Vue.use(Steps);
Vue.use(Dialog);
Vue.use(Tooltip);
Vue.use(Popover);
Vue.use(Card);
Vue.use(Carousel);
Vue.use(CarouselItem);
Vue.use(Collapse);
Vue.use(Timeline);
Vue.use(Divider);
Vue.use(Image);
// Vue.use(MessageBox);
Vue.use(Loading.directive);
Vue.prototype.$loading = Loading.service;
Vue.prototype.$notify = MessageBox.confirm;
Vue.prototype.$notify = Notification;
Vue.prototype.$message = Message;
同理其他UI 组件也能这样使用。 按需引入是减少代码体积一个很重要的