1、为了提升性能,将懒加载的文件单独打包
在webpack.config.js配置打包成chunks
// 打包到不同的chunks
optimization: {
// 将动态加载(懒加载)的文件(imort())单独打包
splitChunks: {
chunks: "all",
},
// 避免分割缓存失效
runtimeChunk: {
name: (entrypoint) => `runtime~${entrypoint.name}`,
},
},
2、React使用路由懒加载前后对比
(1)不使用路由懒加载
import { Link, Routes, Route } from "react-router-dom"
import Home from "./pages/Home";
import About from "./pages/About";
function App() {
return (
<div>
<h1>App</h1>
<ul>
<li>
<Link to="/home">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
<Routes>
<Route path="/home" element={<Home></Home>} />
<Route path="/about" element={<About></About>} />
</Routes>
</div>
)
}
不同路由文件打包到一个文件内
(2)使用路由懒加载
import React, { Suspense, lazy } from "react";
import { Link, Routes, Route } from "react-router-dom"
const Home = lazy(() => import("./pages/Home"));
const About = lazy(() => import("./pages/About"));
function App() {
return (
<div>
<h1>App</h1>
<ul>
<li>
<Link to="/home">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
<Suspense fallback={<div>loading...</div>}>
<Routes>
<Route path="/home" element={<Home></Home>} />
<Route path="/about" element={<About></About>} />
</Routes>
</Suspense>
</div>
)
}
export default App;
初始跳转到Home路由只加载Home的chunk文件
点击跳转到About路由开始加载About的chunk文件
3、Vue使用路由懒加载前后对比
使用vue-loder
// router/index.js
import { createRouter, createWebHashHistory } from 'vue-router'
const Home = () => import('../views/Home')
const About = () => import('../views/About')
const routes = [
{ path: '/', redirect: '/home' },
{ path: '/home', name: 'home', component: Home },
{ path: '/about', name: 'about', component: About },
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
// App.vue
<template>
<ul>
<li>
<router-link to="/home">Home</router-link>
</li>
<li>
<router-link to="/about">About</router-link>
</li>
</ul>
<router-view />
</template>
<script setup>
import { ref, reactive } from 'vue';
</script>
<style style="less" scoped></style>
初始跳转到Home路由只加载Home的chunk文件
点击跳转到About路由开始加载About的chunk文件