隨着單頁應用發展的愈來愈龐大,拆分js就是第一要務,拆分後的js,就能夠根據咱們需求來有選擇性的加載了。javascript
因此第一個問題,就是js怎麼拆?html
來個demo,先看一下未拆分以前是什麼樣子: a.js:java
import b from './b.js';
console.log("this is a.js")
const btn = document.querySelector("#btn");
btn.onclick = ()=>{
b();
}
複製代碼
b.js:node
export default ()=>{
console.log("this is b");
}
複製代碼
html:react
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="btn">btn</div>
<script src="./dist/main.js"></script>
</body>
</html>
複製代碼
webpack.config.jswebpack
module.exports = {
entry:'./a.js',
output:{
filename:'[name].js'
}
}
複製代碼
module.exports = {
entry:'./a.js',
output:{
filename:'[name].js',
chunkFilename:'[name].js'// 設置按需加載後的chunk名字
}
}
複製代碼
這裏就添加了一句,chunkFilename而已,chunkFilename的做用就是用來給拆分後的chunk們起名字的配置項。 ok,執行webpackes6
仍是隻打包出了一個main.js,毫無變化... 不用擔憂,這是由於還有設置沒搞定。web
// import b from './b.js';
console.log("this is a.js")
const btn = document.querySelector("#btn");
btn.onclick = ()=>{
import('./b').then(function(module){
const b = module.default;
b();
})
}
複製代碼
輸出文件變成了兩個,1個main.js、1個1.js 這個1.js很迷...express
查看一下源碼,能夠看出來,它其實就是咱們的b.jsnpm
總結一下 :
額,成功報錯了...腦闊疼 分析報錯:
該配置能幫助你爲項目中的全部資源指定一個基礎路徑。它被稱爲公共路徑(publicPath)
。 修改webpack.config.js
module.exports = {
entry:'./a.js',
output:{
filename:'[name].js',
chunkFilename:'[name].js',// 設置按需加載後的chunk名字
publicPath:'dist/' // 設置基礎路徑
}
}
複製代碼
前面1.js這玩意也不可讀啊,有問題也很難明確,webpack,提供了定義按需chunkname的方式,修改a.js:
// import b from './b.js';
console.log("this is a.js")
const btn = document.querySelector("#btn");
btn.onclick = ()=>{
import(/* webpackChunkName: "b" */ './b').then(function(module){
const b = module.default;
b();
})
}
複製代碼
在動態引入的語法前,添加了註釋,註釋就是爲chunk命明的方式,結果:
輸出了b.js,測試迴歸一次:
先安裝webpack-dev-server,配置npm scripts
{
"devDependencies": {
"webpack-dev-server": "^3.1.9"
},
"scripts": {
"start:dev": "webpack-dev-server"
},
"dependencies": {
"webpack": "^4.20.2",
"webpack-cli": "^3.1.2"
}
}
複製代碼
修改webpack.config.js
var path = require('path');
module.exports = {
entry:'./a.js',
mode:'development',
output:{
filename:'[name].js',
chunkFilename:'[name].js',// 設置按需加載後的chunk名字
publicPath:'dist/'
},
devServer: {
contentBase: './',
compress: true,
port: 9000
}
}
複製代碼
修改webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry:'./a.js',
mode:'development',
output:{
filename:'[name].js',
chunkFilename:'[name].js',// 設置按需加載後的chunk名字
publicPath:'dist/'
},
devServer: {
contentBase: './',
compress: true,
port: 9000,
hot: true, // 開啓熱更新
},
plugins: [ // 開始熱更新
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
],
}
複製代碼
上面一共起做用的就是3句話:
// import b from './b.js';
console.log("this is a.js")
const btn = document.querySelector("#btn");
btn.onclick = ()=>{
import(/* webpackChunkName: "b" */ './b').then(function(module){
const b = module.default;
b();
})
}
if (module.hot) {// 開啓熱替換
module.hot.accept()
}
複製代碼
ok,就這麼簡單,熱更新+按需加載就齊活了。
業務中,除了點擊的時候按需加載,還有大部分場景都是在路由切換的時候進行按需加載
修改webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry:'./a.js',
mode:'development',
output:{
filename:'[name].js',
chunkFilename:'[name].js',// 設置按需加載後的chunk名字
publicPath:'dist/'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
}
}
]
},
devServer: {
contentBase: './',
compress: true,
port: 9000,
hot: true,
},
plugins: [
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
],
}
複製代碼
上面新增的就是添加了一個babel-loader
{
"presets": ["@babel/preset-react","@babel/preset-env"]
}
複製代碼
修改a.js
import React,{Component} from 'react';
import ReactDom from 'react-dom';
import B from './b.js';
export default class A extends Component{
render(){
return <div> this is A <B /> </div>
}
}
ReactDom.render(<A/>,document.querySelector("#btn"))
if (module.hot) {
module.hot.accept()
}
複製代碼
修改b.js
import React,{Component} from 'react';
export default class B extends Component{
render(){
return <div>this is B</div>
}
}
複製代碼
測試一下:
react按需加載進化了好幾個方式,目前最新的方式就是使用react-loadable這個組件 官方也推薦使用這個庫來實現,目前這個庫已經1w+star了
修改a.js
import React,{Component} from 'react';
import { BrowserRouter as Router, Route, Switch,Link } from 'react-router-dom';
import ReactDom from 'react-dom';
import Loadable from 'react-loadable';
const Loading = () => <div>Loading...</div>;
const B = Loadable({
loader: () => import('./b.js'),
loading: Loading,
})
const C = Loadable({
loader: () => import('./C.js'),
loading: Loading,
})
export default class A extends Component{
render(){
return <div>
<Router>
<div>
<Route path="/B" component={B}/>
<Route path="/C" component={C}/>
<Link to="/B">to B</Link><br/>
<Link to="/C">to C</Link>
</div>
</Router>
</div>
}
}
ReactDom.render(<A/>,document.querySelector("#btn"))
if (module.hot) {
module.hot.accept()
}
複製代碼
點擊跳轉toC
能夠看到加載了1.js,也就是說異步加載順利完成 可是如今存在問題:在/C路徑下刷新,會出現沒法命中路由的狀況
var express = require('express')
var app = express()
app.use(express.static('dist'))
app.get('*', function (req, res) {
res.send(`<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="btn">btn</div> <script src="./main.js"></script> </body> </html>`)
})
app.listen(5000);
複製代碼
建立一個簡單的express應用:
路由一個很常見的功能就是路由嵌套,因此咱們的按需加載必須支持嵌套路由纔算合理 修改a.js
import React,{Component} from 'react';
import { BrowserRouter as Router, Route, Switch,Link } from 'react-router-dom';
import ReactDom from 'react-dom';
import Loadable from 'react-loadable';
const Loading = (props) => {
return <div>Loading...</div>
};
const B = Loadable({
loader: () => import('./b.js'),
loading: Loading,
})
const C = Loadable({
loader: () => import('./c.js'),
loading: Loading,
})
export default class A extends Component{
render(){
return <div>
<Router>
<div>
<Route path="/B" component={B}/>
<Route path="/C" component={C}/>
<Link to="/B">to B</Link><br/>
<Link to="/C">to C</Link>
</div>
</Router>
</div>
}
}
ReactDom.render(<A/>,document.querySelector("#btn"))
if (module.hot) {
module.hot.accept()
}
複製代碼
修改c.js
import React,{Component} from 'react';
import { Route,Link} from 'react-router-dom';
import Loadable from 'react-loadable';
const Loading = (props) => {
return <div>Loadingc...</div>
};
const D = Loadable({
loader: () => import('./d.js'),
loading: Loading,
})
export default class C extends Component{
render(){
return <div> this is C <Route path="/C/D" component={D}/> <Link to="/C/D">to D</Link> </div> } } 複製代碼
入口沒問題
點擊跳轉動態加載C沒問題
點擊跳轉D不行了
能夠看到動態引入資源./d.js的時候,出現了異常,莫名其妙的添加了路徑/C
這裏疑惑了好一會,還查了不少內容,最後痛定思痛察覺到應該仍是publicPath設置有問題,從新檢查了設置,修改webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry:'./a.js',
mode:'development',
output:{
path:path.resolve(__dirname, 'dist'),
filename:'[name].js',
chunkFilename:'[name].js',// 設置按需加載後的chunk名字
publicPath:'/dist/'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
}
}
]
},
devServer: {
contentBase: './',
compress: true,
port: 9000,
hot: true,
},
plugins: [
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
],
}
複製代碼
這裏惟一的改動,就是publicPath由原來的dist/,變成/dist/,只要把前面的路徑補上,就不會去找相對的地址了。
前面看似解決了問題,但在真實場景下,咱們的要求確定會更高! 首先就是要封裝一個便捷使用的按需加載組件。
理想很美好,現實很骨幹
const LazyLoad = (path)=>{
return Loadable({
loader: () => import(path),
loading: Loading,
})
}
const B = LazyLoad('./b.js')
複製代碼
而後就收穫了報錯
這是由於webpack編譯的時候import預發==不支持動態路徑==
import不支持動態路徑,是由於webpack須要先掃一遍js文件,找出裏面按需加載的部分,進行按需打包,但不會關心內部的js執行上下文,也就是說,在webpack掃描的時候,js中的變量並不會計算出結果,因此import不支持動態路徑。
既然import不能搞,那隻能封裝非import的部分了
const LazyLoad = loader => Loadable({
loader,
loading:Loading,
})
複製代碼
把loader這部分看成參數分離出去,下面就是具體的使用
const B = LazyLoad(()=>import('./b.js'));
const C = LazyLoad(()=>import('./c.js'));
複製代碼
下面是所有代碼
import React,{Component} from 'react';
import { BrowserRouter as Router, Route, Switch,Link } from 'react-router-dom';
import ReactDom from 'react-dom';
import Loadable from 'react-loadable';
const Loading = (props) => {
return <div>Loading...</div>
};
const LazyLoad = loader => Loadable({
loader,
loading:Loading,
})
const B = LazyLoad(()=>import('./b.js'));
const C = LazyLoad(()=>import('./c.js'));
export default class A extends Component{
render(){
return <div>
<Router>
<div>
<Route path="/B" component={B}/>
<Route path="/C" component={C}/>
<Link to="/B">to B</Link><br/>
<Link to="/C">to C</Link>
</div>
</Router>
</div>
}
}
ReactDom.render(<A/>,document.querySelector("#btn"))
if (module.hot) {
module.hot.accept()
}
複製代碼
上面的封裝方式並非十分完美,webpack文檔上說支持: ==import(./dynamic/\${path}
)的方式== 只要不全是變量貌似也是支持的,這就要看具體的業務形態了,若是按需的部分都在某個目錄下,這種操做或許更溫馨一些。
按目前的方式的話,看似比較繁瑣,不過能夠經過配置webpack的alias別名來進行路徑支持。
react router除了組件方式之外,還能夠經過config的方式來進行配置,config的方式便於統一維護controller層。
建立LazyLoad.js文件
import React from 'react';
import Loadable from 'react-loadable';
const Loading = (props) => {
return <div>Loading...</div>
};
export default loader => Loadable({
loader,
loading:Loading,
})
複製代碼
首先把Lazyload組件單獨封裝出去
建立routes.js
import LazyLoad from './LazyLoad';
export default [
{
path: "/B",
component: LazyLoad(()=>import('./b.js'))
},
{
path: "/C",
component: LazyLoad(()=>import('./c.js')),
routes: [
{
path: "/C/D",
component: LazyLoad(()=>import('./d.js'))
},
{
path: "/C/E",
component: LazyLoad(()=>import('./e.js'))
}
]
}
];
複製代碼
配置routes文件,用來動態引入路由
建立utils.js
import React from 'react';
import {Route} from 'react-router-dom';
export const RouteWithSubRoutes = route => (
<Route
path={route.path}
render={props => (
// pass the sub-routes down to keep nesting
<route.component {...props} routes={route.routes} />
)}
/>
);
複製代碼
==這一步特別重要、特別重要、特別重要==
這個工具方法的做用就是將組件渲染出來
import React,{Component} from 'react';
import { BrowserRouter as Router, Route, Switch,Link } from 'react-router-dom';
import ReactDom from 'react-dom';
import {RouteWithSubRoutes} from './utils';
import routes from './routes';
export default class A extends Component{
render(){
return <div> <Router> <div> <Link to="/B">to B</Link><br/> <Link to="/C">to C</Link> {routes.map((route, i) => <RouteWithSubRoutes key={i} {...route} />)} </div> </Router> </div> } } ReactDom.render(<A/>,document.querySelector("#btn")) if (module.hot) { module.hot.accept() } 複製代碼
==注意:這裏只處理了第一層路由== ==注意:這裏只處理了第一層路由== ==注意:這裏只處理了第一層路由==
路由配置化以後,嵌套子路由要以函數式來書寫
import React,{Component} from 'react';
import {RouteWithSubRoutes} from './utils';
import { Link} from 'react-router-dom';
export default ({ routes }) => (
<div> this is C <Link to="/C/D">to D</Link> <Link to="/C/E">to E</Link> {routes.map((route, i) => <RouteWithSubRoutes key={i} {...route} />)} </div> ); 複製代碼
==注意:config嵌套路由,須要逐層,一層一層的經過RouteWithSubRoutes來渲染。== ==新人很容易忽視這一點!== ==新人很容易忽視這一點!== ==新人很容易忽視這一點!==
前面使用config的方式配置了路由,但其實這裏也能夠混用,就是config方式+組件的方式混合使用。 修改二級路由入口:
import React from 'react';
import { Link,Route} from 'react-router-dom';
//import {RouteWithSubRoutes} from './utils';
import LazyLoad from './LazyLoad';
const D = LazyLoad(() => import('./d.js'))
const E = LazyLoad(() => import('./e.js'))
export default ({ routes }) => (
<div>
this is C
<Route path="/C/D" component={D}/>
<Route path="/C/E" component={E}/>
<Link to="/C/D">to D</Link>
<Link to="/C/E">to E</Link>
{/* {routes.map((route, i) => <RouteWithSubRoutes key={i} {...route} />)} */}
</div>
);
複製代碼
其實,這裏的話,就是隨便搞了
路由的話,仍是統一維護爲好,固然也能夠根據業務來自主選擇須要的方式!。
腦闊疼的webpack按需加載告一段落了。