yma16-logo

前言

大家好,我是yma16,本文分享vue2_按需引入elment、echarts和路由懒加载,减少打包体积
前端打包概念
前端打包是指将多个前端资源文件(如 HTML、CSS、JavaScript 文件、图片、字体等)合并、压缩、混淆等处理后,生成一个或多个文件用于部署到生产环境。打包可以提高页面加载速度、减少网络请求次数、保障代码安全性等。

常见的前端打包工具有 webpack、Rollup、Parcel 等。这些工具可以根据配置将多个模块打包成单个文件,也可以进行代码分离、按需加载、缓存等优化,同时也支持多种前端框架和库。

响应慢

在这里插入图片描述

25s这个响应和我的拖延症有得一拼
在这里插入图片描述

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。
本文分享到这结束,如有错误或者不足之处欢迎指出,感谢大家的阅读!

在这里插入图片描述

Logo

前往低代码交流专区

更多推荐