vue_按需引入elment、echarts和路由懒加载,减少打包体积

简介: vue_按需引入elment、echarts和路由懒加载,减少打包体积

@TOC

响应慢

image.png

25s这个响应和我的拖延症有得一拼
image.png

element的按需引入

定义一个函数按需引入组件,再main的入口调用,把vue传递进来

import {
   
   
    Container,
    Header,
    Aside,
    Main,
    Footer,
    Message,
    Form,
    Button,
    Table,
    TableColumn,
    Drawer,
    Input,
    Card,
    Menu,
    Submenu,
    MenuItem,
    MenuItemGroup,
    FormItem,
    Avatar,
    Link,
    Loading,
    Pagination,
    Alert,
    Notification,
    Select
} from 'element-ui'

const importElementComponents = (Vue) => {
   
   
    Vue.use(Container)
    Vue.use(Header)
    Vue.use(Main)
    Vue.use(Aside)
    Vue.use(Footer)
    Vue.use(Form)
    Vue.use(FormItem)
    Vue.use(Button)
    Vue.use(Table)
    Vue.use(TableColumn)
    Vue.use(Drawer)
    Vue.use(Input)
    Vue.use(Card)
    Vue.use(MenuItem)
    Vue.use(Menu)
    Vue.use(Submenu)
    Vue.use(MenuItemGroup)
    Vue.use(Avatar)
    Vue.use(Link)
    Vue.use(Loading)
    Vue.use(Pagination)
    Vue.use(Alert)
    Vue.use(Select)
    Vue.prototype.$message = Message
    Vue.prototype.$notify = Notification
}

export default importElementComponents

babelrc文件添加配置
module:false
plugin: component

{
   
   
  "presets": [
    [
      "env",
      {
   
   
        "modules": false,
        "targets": {
   
   
          "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
        }
      }
    ],
    "stage-2"
  ],
  "plugins": [
    [
      "component",
      {
   
   
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ],
    "transform-vue-jsx",
    "transform-runtime"
  ],
  "env": {
   
   
    "test": {
   
   
      "presets": ["env", "stage-2"]
    }
  }
}

echarts的按需引入

定义一个函数按需引入组件,再main的入口调用,把vue传递进来

// 引入 echarts 核心模块,核心模块提供了 echarts 使用必须要的接口。
import * as echarts from 'echarts/core'
// 引入柱状图图表,图表后缀都为 Chart

import {
   
    BarChart, LineChart, MapChart, GraphChart, PieChart} from 'echarts/charts'
// 引入提示框,标题,直角坐标系,数据集,内置数据转换器组件,组件后缀都为 Component
import {
   
   
    TitleComponent,
    TooltipComponent,
    GridComponent,
    DatasetComponent,
    TransformComponent,
    ToolboxComponent
} from 'echarts/components'
// 标签自动布局,全局过渡动画等特性
import {
   
    LabelLayout, UniversalTransition } from 'echarts/features'
// 引入 Canvas 渲染器,注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import {
   
    CanvasRenderer } from 'echarts/renderers'

// 注册必须的组件
echarts.use([
    TitleComponent,
    TooltipComponent,
    GridComponent,
    DatasetComponent,
    TransformComponent,
    BarChart,
    LineChart,
    MapChart,
    GraphChart,
    PieChart,
    LabelLayout,
    UniversalTransition,
    CanvasRenderer,
    ToolboxComponent
])
const importEchartsComponents = (Vue) => {
   
   
    Vue.prototype.$echarts = echarts// 绑定echarts
}
export default importEchartsComponents

路由懒加载

传统的 import '组件' 改为函数调用
使用hidden:hidden,调用组件才会渲染

import {
   
    isEmpty } from '@/utils'
import store from '@/store'
const Article = () => import('@/components/Article')
const Login = () => import('@/components/Login')
const Register = () => import('@/components/Register')
const Onlinewebsocket = () => import('@/components/Onlinewebsocket')
const Home = () => import('@/components/Home')
const Bilicom = () => import('@/components/Bilicom')
const Mavoneditor = () => import('@/components/Mavoneditor')
const GrilShow = () => import('@/components/GrilShow')
const Csslearn = () => import('@/components/Csslearn')

const defaultRoutes = [
    {
   
   
        path: '/',
        name: 'Article',
        component: Article,
        hidden: true
    },
    {
   
   
        path: '/login',
        name: 'Login',
        component: Login,
        hidden: true
    },
    {
   
   
        path: '/register',
        name: 'Register',
        component: Register,
        hidden: true
    },
    {
   
   
        path: '/home',
        name: 'Home',
        component: Home,
        hidden: true
    },
    {
   
   
        path: '/onlinewebsocket',
        name: 'Onlinewebsocket',
        component: Onlinewebsocket,
        hidden: true
    },
    {
   
   
        path: '/bilicom',
        name: 'Bilicom',
        component: Bilicom,
        hidden: true
    },
    {
   
   
        path: '/mavoneditor',
        name: 'Mavoneditor',
        component: Mavoneditor,
        hidden: true
    },
    {
   
   
        path: '/gril',
        name: 'grilshow',
        component: GrilShow,
        hidden: true
    },
    {
   
   
        path: '/css',
        name: 'css',
        component: Csslearn,
        hidden: true
    }
]

const useRouter = (Vue, VueRouter) => {
   
   
    let routes = [
        ...defaultRoutes
    ]
    const originalPush = VueRouter.prototype.push
    VueRouter.prototype.push = function push (location) {
   
   
        return originalPush.call(this, location).catch((err) => err)
    }
    // 路由
    const router = new VueRouter({
   
   
        routes
    })

    // const whiteList = ['/login', '/register']

    router.beforeEach(async (to, from, next) => {
   
   
        let yma16siteUserInfo = localStorage.getItem('yma16siteUserInfo')
            ? JSON.parse(localStorage.getItem('yma16siteUserInfo'))
            : ''
        let name = yma16siteUserInfo.username
        let pwd = yma16siteUserInfo.password

        let hasToken = {
   
   
            name: name,
            password: pwd
        }
        console.log('localStorage', hasToken)
        if (hasToken.name && hasToken.password) {
   
   
            if (isEmpty(store.state.user.userInfo)) {
   
   
                // 空的 modules下的user
                console.log('路由的登录认证')
                // 用户自主登录
                await store.dispatch('user/loginUserInfo', hasToken)
                next()
            } else {
   
   
                next()
            }
        } else {
   
   
            // next({ path: "/login" }); //去登录
            next()
        }
    })

    Vue.use(VueRouter)
    return router
}

export default useRouter

我的main文件

将Vue作为参数传入为了方便后续的cdn配置修改简单

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import VueRouter from 'vue-router'
import axios from 'axios'
import cookies from 'vue-cookies'
import hljs from 'highlight.js'
import useRouter from './router'
import App from './App'
import importElementComponents from './importElement'
import importEchartsComponents from './importEchartsComponents'

// 样式
import 'github-markdown-css/github-markdown.css'
import 'highlight.js/styles/github.css'
import 'nprogress/nprogress.css'

// 路由
const router = useRouter(Vue, VueRouter)

// 按需引入elementui
importElementComponents(Vue)

// 按需引入echarts
importEchartsComponents(Vue)

Vue.config.productionTip = false
Vue.use(cookies)

Vue.use(hljs)
Vue.directive('highlight', function (el) {
   
   
    const blocks = el.querySelectorAll('pre code')
    blocks.forEach(block => {
   
   
        hljs.highlightBlock(block)
    })
})
// cookie
Vue.prototype.$cookies = cookies
// axios
Vue.prototype.$axios = axios
window.$axios_w = axios

Vue.prototype.$cookies.set('user_session', 'null')

new Vue({
   
   
    el: '#app',
    router,
    components: {
   
    App },
    template: '<App/>'
})

结束

仓库:https://gitcode.net/qq_38870145/myblogvue_django
浏览地址:https://yongma16.xyz/
30几块的1核2G服务器带宽过于小1M,造成很卡,后续采用考虑采用cdn

目录
相关文章
|
6天前
|
JavaScript
【vue】如何跳转路由到指定页面位置
【vue】如何跳转路由到指定页面位置
19 0
|
6天前
|
移动开发 JavaScript 应用服务中间件
vue打包部署问题
Vue项目`vue.config.js`中,`publicPath`设定为&quot;/h5/party/pc/&quot;,在线环境基于打包后的`dist`目录,而非Linux的`/root`。Nginx代理配置位于`/usr/local/nginx/nginx-1.13.7/conf`,包含两个相关配置图。
vue打包部署问题
|
6天前
|
JavaScript 数据可视化 算法
vue3+threejs可视化项目——搭建vue3+ts+antd路由布局(第一步)
vue3+threejs可视化项目——搭建vue3+ts+antd路由布局(第一步)
38 6
|
5天前
|
存储 数据可视化 前端开发
Echarts+vue+java+mysql实现数据可视化
Echarts+vue+java+mysql实现数据可视化
|
5天前
|
资源调度 JavaScript 前端开发
阿珊详解Vue路由的两种模式:hash模式与history模式
阿珊详解Vue路由的两种模式:hash模式与history模式
|
6天前
|
JavaScript
vue中watch监听路由传来的参数变化问题
vue中watch监听路由传来的参数变化问题
8 0
|
6天前
|
缓存 JavaScript
在 Vue 组件中使用计算属性和侦听器来响应路由变化
【5月更文挑战第8天】Vue Router 中,计算属性和侦听器常用于根据路由变化更新组件状态。计算属性缓存依赖,当路由参数改变时自动更新,如示例中的 `userId`。侦听器则监听 `$route` 变化,执行相应操作,例如在 `currentUserId` 示例中响应 `userId` 更新。计算属性适合简单变化,而异步操作或复杂场景可选用侦听器。Vue 3 中,`watchEffect` 减少了部分侦听场景的复杂性。总之,它们用于组件内部响应路由变化,而非直接处理路由逻辑。
20 4
|
6天前
|
资源调度 JavaScript 前端开发
【vue】vue中的路由vue-router,vue-cli脚手架详细使用教程
【vue】vue中的路由vue-router,vue-cli脚手架详细使用教程
|
6天前
|
JavaScript Go
Vue路由跳转及路由传参
Vue路由跳转及路由传参
|
6天前
|
JavaScript 前端开发
vue3+ts+element home页面侧边栏+头部组件+路由组件组合页面教程
这是一个Vue.js组件代码示例,展示了带有侧边栏导航和面包屑导航的布局。模板中使用Element Plus组件库,包含可折叠的侧边栏,其中左侧有 Logo 和导航列表,右侧显示更具体的子菜单。`asideDisplay`控制侧边栏宽度。在`script`部分,使用Vue的响应式数据和生命周期钩子初始化路由相关数据,并从localStorage恢复状态。样式部分定义了组件的颜色、尺寸和布局。
29 1