webpack中的懒加载


本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/06/20/webpack%E4%B8%AD%E7%9A%84%E6%87%92%E5%8A%A0%E8%BD%BD/

摘要

本文主要讲述了:

  1. 反面示例
  2. 正面示例

正文

懒加载,又名按需加载,是指在用到对应模块的时候再去加载。

反面示例

learn_webpack/webpack.config.js

1
2
3
4
5
6
7
8
9
10
module.exports = {
mode: 'development',
entry: {
index: './src/index.js',
},
output: {
filename: '[name].bundle.js',
chunkFilename: '[name].bundle.js',
},
};

learn_webpack/src/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
function getComponent() {
return import(/* webpackChunkName: "lodash" */ 'lodash')
.then(({ default: _ }) => {
const element = document.createElement('div');
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
})
.catch((error) => 'An error occurred while loading the component');
}

getComponent().then((component) => {
document.body.appendChild(component);
});

这个示例虽然把lodash进行了按需加载,但实际上,由于页面必须用到lodash,按需加载不过额外增加了一次网络请求,反而浪费了性能,并没有实现性能优化的目的。

正面示例

learn_webpack/webpack.config.js

1
2
3
4
5
6
7
8
9
10
module.exports = {
mode: 'development',
entry: {
index: './src/index.js',
},
output: {
filename: '[name].bundle.js',
chunkFilename: '[name].bundle.js',
},
};

learn_webpack/src/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import _ from 'lodash';

function component() {
const element = document.createElement('div');

const button = document.createElement('button');
const br = document.createElement('br');

button.innerHTML = 'Click me and look at the console!';
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
element.appendChild(br);
element.appendChild(button);

// Note that because a network request is involved, some indication
// of loading would need to be shown in a production-level site/app.
button.onclick = (e) =>
import(/* webpackChunkName: "print" */ './print').then((module) => {
const print = module.default;
print();
});

return element;
}

document.body.appendChild(component());

learn_webpack/print.js

1
2
3
4
5
6
7
console.log(
'The print.js module has loaded! See the network tab in dev tools...'
);

export default () => {
console.log('Button Clicked: Here\'s "some text"!');
};

此示例将按钮的点击事件按需加载,只要用户不点击按钮,点击事件就是不需要的。因此实现了性能优化的目的。

参考资料

本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/06/20/webpack%E4%B8%AD%E7%9A%84%E6%87%92%E5%8A%A0%E8%BD%BD/


本文对你有帮助?请支持我


支付宝
微信