深入浅谈 webpack

```js /*/ // install a JSONP callback for chunk loading // function webpackJsonpCallback(data) { // var chunkIds = data[0]; // var moreModules = data[1]; // var executeModules = data[2]; // // // add "moreModules" to the modules object, // // then flag all "chunkIds" as loaded and fire callback // var moduleId, chunkId, i = 0, resolves = []; // for(;i < chunkIds.length; i++) { // chunkId = chunkIds[i]; // if(installedChunks[chunkId]) { // resolves.push(installedChunks[chunkId][0]); // } // installedChunks[chunkId] = 0; /*/ }

/*/ while(resolves.length) { // resolves.shift()(); /*/ } ```

提取公共代码

提取公共代码主要依赖于 SplitChunksPlugin

wb-course-010.png

示例参考 demo106

diff optimization: { runtimeChunk: 'single', // 抽离 rumtime 到单独文件 + splitChunks: { + cacheGroups: { + common: { + name: 'common', + chunks: 'all', + minSize: 0, + minChunks: 2, + }, + }, + }, }, plugins: [new HtmlWebpackPlugin({ title: 'webpack demo' })],

构建出来的 common 模块和 moduleA moduleB 模块有什么区别?

输出分析

缓存及并发

在整个 webpack 构建流程中,loader 对文件的转换和代码压缩是最耗时的过程,前者需要处理大量数据(模块),后者需要抽象成 AST 然后应用各种规则分析和处理,整个过程计算量巨大。文件读写和计算操作是无法避免的,那能不能让 webpack 同一时刻处理多个任务,发挥多核 CPU 电脑的威力,以提升构建速度呢?

由于 JavaScript 是单线程模型,要想发挥多核 CPU 的能力,只能通过多进程去实现,而无法通过多线程实现。

实际案例

common 代码额外分组

```js function getJsGroups(entries) { /* ... */

return { common: { name: 'common', minChunks: 2, priority: 10, chunks: 'all', // extract all css in common-pre and put it in the header so when some // dynamic chunk need the common.css it won't load again test: (module, chunks) => module.type !== 'css/mini-extract' && !chunks.some(chunk => preGroup.includes(chunk.name)), }, 'common-pre': { name: 'common-pre', minChunks: 2, priority: 1, chunks: 'all', }, }; } ```

合并样式文件

```js compiler.hooks.emit.tap('CombineCssPlugin', compilation => { const { entry, appendRule } = this.options; const { chunks, assets } = compilation;

/* ... */

Object.entries(cssFiles).forEach(([group, files]) => { /* ... */

const content = files
  .map(file => (assets[file].source && assets[file].source()) || '')
  .join('\n');

if (content.length > 400 * 1024) {
  logger.yellow(`cssGroup [${group}] 大于 400KB 请注意合理分组!!!`);
}

const hash = createHash('md5')
  .update(content)
  .digest('hex')
  .slice(0, 7);

const newFile = `${relativeDist}/${group}_${hash}.css`;

assets[newFile] = new RawSource(content);

// delete used, needn't emit this source
files.forEach(file => {
  logger.green(`deleting ${file}, which has been merged in ${newFile}...`);

  delete assets[file];
});

}); }); ```

小结

通过此次课程希望各位对 webpack 的构建流程以及构建代码的执行流程能有一个初步的了解。此次课程更多是把 webpack 的各个点拆开了给大家介绍,如果各位能从一到两个点上获得启发,那我认为就是物有所值的。webpack 的终极威力是要把这些零碎的点组织成一个完整的配置,这样才能体现它的效率。这方面的介绍,~~还请大家持续关注后续课程~~(可能太无聊了,我并不会写)。

扩展阅读

-->
loading...
loading...

最新评论

    还没有人评论...

Powered by Fun & Rainsho. Copyright © 2017. [Manage]

www.rainsho.cc. All rights reserved.