Taro 分包异步化踩坑指南
# Taro 分包异步化踩坑指南
# 分析
安装 webpack-bundle-analyzer
分析依赖,找出体积大的第三方包
# 配置 webpack 进行文件拆分
先添加拆包配置
const reg1 = /[\\/]demo1[\\/]/;
const reg2 = /[\\/]demo2[\\/]/;
mini.webpackChain = (chain) => {
// 获取 Taro 默认的 splitChunks 配置
const splitChunks = chain.optimization.get("splitChunks");
// 拆离出公共包
splitChunks.cacheGroups = {
...splitChunks.cacheGroups,
demo1: {
test: reg1,
name: "demo1",
chunks: "all",
},
demo2: {
test: reg2,
name: "demo2",
chunks: "all",
}
}
chain.optimization.splitChunks({
...splitChunks,
});
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
在小程序引入的时候,引入新拆包的文件
// "runtime", "vendors", "taro", "common" 是 Taro 框架自带的配置
mini.commonChunks = ["runtime", "vendors", "taro", "common", "demo1","demo2"]
1
2
2
结果:文件实现了拆分,但是加载主包时仍然会加载拆分的包,且代码无法按通过 webpack 的 require 进行按需加载
总结:按需加载无法得到实现,webpack 的拆包对小程序意义不大
改进方案:基于小程序的 require 通过自定义 Taro 插件修改配置进行按需加载
# 小程序分包异步化
import type { IPluginContext } from '@tarojs/service'
import type Config from 'webpack-chain'
import { statSync, copyFileSync } from 'fs'
import { copySync } from 'fs-extra'
import { resolve, basename } from 'path'
interface WXRequireAsyncPluginOptions {
sources: string[]
dest: string
}
export default (ctx: IPluginContext, options: WXRequireAsyncPluginOptions) => {
ctx.modifyWebpackChain(({ chain }: { chain: Config }) => {
chain
.merge({
// 定义 wx_require 为微信小程序中的 require
externals: {
wx_require: 'require',
},
})
.plugin('provide-plugin')
.use(require('webpack').ProvidePlugin, [
{
wx_require: 'wx_require',
},
])
})
// 把用 wx_require 的文件移到输出目录中
ctx.onBuildFinish(() => {
const { sources, dest } = options
sources.forEach(source => {
const stat = statSync(source)
if (stat.isDirectory()) {
copySync(source, dest)
} else {
copyFileSync(source, resolve(dest, basename(source)))
}
})
})
}
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
let weappConfig = {
sourceRoot: 'src',
outputRoot: 'dist-weapp',
env: {
COMPILE_TYPE: '"weapp"',
},
plugins: [
resolve(__dirname, '../scripts/taro.modify.config.plugin.ts'),
[
resolve(__dirname, '../scripts/taro.wx_require_async.plugin.ts'),
{
sources: PRIVATIZE ? [
resolve(__dirname, '../src/lib/sdk.private.js'),
resolve(__dirname, '../src/lib/im.private.js'),
] : [
resolve(__dirname, '../demo1/'),
resolve(__dirname, '../demo2/'),
],
dest: resolve(__dirname, '../dist-weapp')
},
],
],
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
结果:代码可以按需加载,但在按需加载的代码未从主包拆分出来
总结:主包的体积未得到拆分
改进方案:将按需加载的代码提取到分包
编辑 (opens new window)
上次更新: 2024/01/26, 18:22:27