03-资源分离

135 阅读2分钟

资源分离

entry.dependOn 手动配置

dependOn 表示当前chunk依赖的其他chunk

const entry = {
  // key => chunk 打包之后的名称
  index: {
    // chunk 对应的路径
    import: resolve(__dirname, 'src/entry/index.js'),
    // 本入口依赖的其它chunk
    dependOn: ['shared', 'my_math'], // 依赖的chunk
  },
  second: {
    import: resolve(__dirname, 'src/entry/second.js'),
    dependOn: ['shared', 'my_math'],
  },
  // 将 lodash 打包成 名称为 shared chunk
  shared: 'lodash',
  // 将 该路径下的资源打包成名称为 my_math 的 chunk,来能被复用
  my_math: resolve(__dirname, 'src/utils/math.js')
}

注意事项:

  • 路径为资源所在的路径,如果非相对路径,那么则自动的解析为node_modules里的包(其实就是import的路径语法规则)
  • dependOn 为依赖的 chunk数组,对该入口文件进行检查,如果内部有引用对应的文件依赖则直接使用dependOn中的chunk
  • dependOn
    • 缺点:需要手动配置自己需要单独打包的资源,特别是一旦入口文件变多,依赖复杂的情况下
    • 优点:能同时处理公共的node_modules的模块和自定义的文件,更细致化

entry.dependOn 手动配置 对应案例:code-example / 05-example

split-chunks-plugin 自动分割

split-chunks-plugin

const optimization = {
  splitChunks: {
    // include all types of chunks
    // initial | async
    chunks: 'all',
  },
}

打包的时候你可能发现不是所有的js文件都被分割了,不要急这是因为 split-chunks-plugin的有四个原则,在之后的《资源缓存》会讲到

代码案例在 code-example / 06-example

动态加载资源import(懒加载和预加载)

  • import 打包 node_modules 的chunk可以和 split-chunks-plugin / 手动的复用
  • import 的原理就是当执行到import的时候创建对应的script标签并执行代码,因此这些chunk都是延时加载(并且是动态的,在打包之后的html里看不见),但是需要注意,效果必须在production模式或者在devServer情况下才能生效(发现在dev情况html模板文件直接的插入了chunk,并没有动态加载)
import(src)
	.then((res: ESModuleExports) => {
  	// 相当于 import * as res from `${src}`
		const { default } = res
    console.log(res, default)
	})
	.catch(errorReason => {
  	console.log('资源加载失败', errorReason)
  }

import 魔法注释

  • import打包之后的chunk名称

    import(/* webpackChunkName: 'srcName' */src);
    
  • import 打包资源的加载方式,预加载(其实就是link的预加载方式)

    import(/* webpackPrefetch: true */src);
    

代码案例在 code-example / 07-example