@taro-hmr-compile/plugin-webpack 0.0.1-alpha.9 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +101 -0
  2. package/dist/compile/hmr-compiler-plugin.d.ts +7 -7
  3. package/dist/compile/hmr-compiler-plugin.js +2 -29
  4. package/dist/compile/hmr-compiler-plugin.js.map +1 -1
  5. package/dist/compile/hmr-output-plugin.d.ts +28 -0
  6. package/dist/compile/hmr-output-plugin.js +145 -0
  7. package/dist/compile/hmr-output-plugin.js.map +1 -0
  8. package/dist/compile/hmr-style-plugin.d.ts +25 -0
  9. package/dist/compile/hmr-style-plugin.js +53 -0
  10. package/dist/compile/hmr-style-plugin.js.map +1 -0
  11. package/dist/compile/lazy-compiler-loader.d.ts +2 -1
  12. package/dist/compile/lazy-compiler-loader.js +112 -10
  13. package/dist/compile/lazy-compiler-loader.js.map +1 -1
  14. package/dist/constants.d.ts +1 -0
  15. package/dist/constants.js +2 -1
  16. package/dist/constants.js.map +1 -1
  17. package/dist/index.d.ts +2 -0
  18. package/dist/index.js +17 -6
  19. package/dist/index.js.map +1 -1
  20. package/dist/patch/hmr-patch-plugin.d.ts +6 -0
  21. package/dist/patch/hmr-patch-plugin.js +53 -4
  22. package/dist/patch/hmr-patch-plugin.js.map +1 -1
  23. package/dist/patch/hmr-patch-processor.d.ts +2 -1
  24. package/dist/patch/hmr-patch-processor.js +37 -21
  25. package/dist/patch/hmr-patch-processor.js.map +1 -1
  26. package/dist/patch/utils.js +3 -3
  27. package/dist/patch/utils.js.map +1 -1
  28. package/package.json +4 -2
  29. package/src/compile/hmr-compiler-plugin.ts +9 -34
  30. package/src/compile/hmr-output-plugin.ts +158 -0
  31. package/src/compile/hmr-style-plugin.ts +70 -0
  32. package/src/compile/lazy-compiler-loader.ts +85 -10
  33. package/src/constants.ts +2 -0
  34. package/src/index.ts +21 -9
  35. package/src/patch/hmr-patch-plugin.ts +53 -5
  36. package/src/patch/hmr-patch-processor.ts +45 -27
  37. package/src/patch/utils.ts +3 -3
  38. package/src/types/taro-service.d.ts +15 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@taro-hmr-compile/plugin-webpack",
3
- "version": "0.0.1-alpha.9",
3
+ "version": "0.0.2",
4
4
  "description": "",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -34,6 +34,7 @@
34
34
  "@types/babel__template": "^7.4.4",
35
35
  "@types/babel__traverse": "^7.28.0",
36
36
  "@types/debug": "^4.1.13",
37
+ "@types/lodash": "^4.17.26",
37
38
  "@types/node": "^22.20.1",
38
39
  "typescript": "^5.8.2",
39
40
  "webpack": "^5.110.3"
@@ -44,8 +45,9 @@
44
45
  "@babel/template": "^7.29.7",
45
46
  "@babel/traverse": "^7.29.8",
46
47
  "@babel/types": "^7.29.8",
47
- "@taro-hmr-compile/core": "0.0.1-alpha.9",
48
+ "@taro-hmr-compile/core": "0.0.2",
48
49
  "debug": "^4.4.3",
50
+ "lodash": "^4.18.1",
49
51
  "tapable": "^2.3.3",
50
52
  "webpack-sources": "^3.5.1"
51
53
  },
@@ -20,18 +20,21 @@ interface TaroNormalModule {
20
20
  loaders: Array<{ loader: string; options?: unknown }>
21
21
  }
22
22
 
23
- type StyleFilename = NonNullable<Compiler['options']['output']['cssFilename']>
24
-
25
23
  export interface HmrCompilerPluginOptions {
26
24
  paths: IPaths
27
25
  appConfig: AppConfig
28
- styleFilename?: StyleFilename
29
26
  debugNamespaces?: string
30
27
  }
31
28
 
32
29
  type CompileRequested = SyncHook<[page: string]>
33
30
 
34
- type ChunkModulesRendered = SyncHook<[source: string, isPageChunk: boolean]>
31
+ interface ChunkModulesRenderedOptions {
32
+ source: string
33
+ isBootstrapChunk: boolean
34
+ chunk: Chunk
35
+ }
36
+
37
+ type ChunkModulesRendered = SyncHook<[options: ChunkModulesRenderedOptions]>
35
38
 
36
39
  export interface HmrCompilerHooks {
37
40
  compileRequested: CompileRequested
@@ -56,8 +59,6 @@ export class HmrCompilerPlugin {
56
59
 
57
60
  private compiler?: Compiler
58
61
 
59
- private hasCompletedInitialBuild = false
60
-
61
62
  // 页面编译请求可能在任意时刻到达。先排队到下一轮 watchRun,避免与正在执行的编译相互覆盖。
62
63
  private readonly pendingFiles = new Set<string>()
63
64
 
@@ -80,7 +81,7 @@ export class HmrCompilerPlugin {
80
81
 
81
82
  static getCompilationHooks(compilation: Compilation): HmrCompilationHooks {
82
83
  if (!HmrCompilerPlugin.compilationHooksMap.get(compilation)) {
83
- const chunkModulesRendered: ChunkModulesRendered = new SyncHook(['source', 'isBootstrapChunk'])
84
+ const chunkModulesRendered: ChunkModulesRendered = new SyncHook(['options'])
84
85
  HmrCompilerPlugin.compilationHooksMap.set(compilation, {chunkModulesRendered})
85
86
  }
86
87
  return HmrCompilerPlugin.compilationHooksMap.get(compilation)!
@@ -134,7 +135,7 @@ export class HmrCompilerPlugin {
134
135
  // 因而 hash、HMR diff 和 hot-update 仍以完整模块图为准。
135
136
  javascriptHooks.renderChunk.tap({name: PLUGIN_NAME, stage: -10_000}, (source, {chunk}) => {
136
137
  const isBootstrapChunk = isPageChunk(chunk)
137
- hmrHooks.chunkModulesRendered.call(source.source().toString(), isBootstrapChunk)
138
+ hmrHooks.chunkModulesRendered.call({source: source.source().toString(), isBootstrapChunk, chunk})
138
139
  return isBootstrapChunk ? new RawSource('{}') : source
139
140
  })
140
141
 
@@ -167,17 +168,6 @@ export class HmrCompilerPlugin {
167
168
  },
168
169
  )
169
170
 
170
- const stage = compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT
171
- compilation.hooks.processAssets.tap({name: PLUGIN_NAME, stage}, () => {
172
- if (!this.hasCompletedInitialBuild && compilation.hash && compilation.errors.length === 0) {
173
- this.emitMissingPageStyleAssets(compilation)
174
- }
175
- })
176
- })
177
-
178
- compiler.hooks.afterEmit.tap(PLUGIN_NAME, compilation => {
179
- const isSuccessful = compilation.errors.length === 0 && Boolean(compilation.hash)
180
- this.hasCompletedInitialBuild = this.hasCompletedInitialBuild || isSuccessful
181
171
  })
182
172
 
183
173
  // 当前批次完成后释放快照;编译期间新进入 pendingFiles 的请求不会被清理。
@@ -204,23 +194,8 @@ export class HmrCompilerPlugin {
204
194
  return Array.from(pages).some(page => compilation.entrypoints.get(page)?.getEntrypointChunk() === chunk)
205
195
  }
206
196
 
207
- /** PageShell 不包含真实页面的样式依赖,为缺失的页面样式补充空资产。 */
208
- private emitMissingPageStyleAssets(compilation: Compilation) {
209
- const {appConfig, styleFilename} = this.options
210
- if (!styleFilename) return
211
-
212
- getAllPages(appConfig).forEach(page => {
213
- const chunk = compilation.entrypoints.get(page)?.getEntrypointChunk()
214
- if (!chunk) return
215
-
216
- const assetName = compilation.getPath(styleFilename, {chunk, contentHashType: 'css/mini-extract'})
217
- if (!compilation.getAsset(assetName)) compilation.emitAsset(assetName, new RawSource(''))
218
- })
219
- }
220
-
221
197
  private reset() {
222
198
  clearCompiledPages(this.options.paths.appPath)
223
- this.hasCompletedInitialBuild = false
224
199
  this.rebuildingFiles.clear()
225
200
  this.pendingFiles.clear()
226
201
  }
@@ -0,0 +1,158 @@
1
+ import {randomUUID} from 'node:crypto'
2
+ import type {NoParamCallback, PathOrFileDescriptor, WriteFileOptions} from 'node:fs'
3
+ import {mkdir, rename, rm, writeFile} from 'node:fs/promises'
4
+ import path from 'node:path'
5
+ import type {Compilation, Compiler, OutputFileSystem} from 'webpack'
6
+
7
+ export const PLUGIN_NAME = 'HmrOutputPlugin'
8
+
9
+ type WriteFile = OutputFileSystem['writeFile']
10
+
11
+ type WriteFileData = string | NodeJS.ArrayBufferView
12
+
13
+ export interface AtomicOutputPluginOptions {
14
+ /** 这些资产仍由 Webpack 生成,但等其他资产输出完成后才按配置顺序发布。 */
15
+ deferredAssets?: readonly string[]
16
+ }
17
+
18
+ interface DeferredOutput {
19
+ data: WriteFileData
20
+ file: string
21
+ }
22
+
23
+ export class HmrOutputPlugin {
24
+ private readonly deferredAssets: readonly string[]
25
+
26
+ private readonly deferredOutputs = new WeakMap<Compilation, Map<string, DeferredOutput>>()
27
+
28
+ constructor(options: AtomicOutputPluginOptions = {}) {
29
+ this.deferredAssets = options.deferredAssets ?? []
30
+ }
31
+
32
+ apply(compiler: Compiler): void {
33
+ const outputFileSystem = compiler.outputFileSystem
34
+
35
+ if (!outputFileSystem) throw new Error(`[${PLUGIN_NAME}] Webpack outputFileSystem 尚未初始化`)
36
+
37
+ compiler.outputFileSystem = this.createOutputFileSystem(compiler, outputFileSystem)
38
+
39
+ // 尽可能在其他 emit tap 之后读取资产,随后 Webpack 才开始物理输出。
40
+ compiler.hooks.emit.tap({name: PLUGIN_NAME, stage: Number.MAX_SAFE_INTEGER}, compilation => {
41
+ if (compilation.errors.length > 0) return
42
+ this.collectDeferredOutputs(compiler, compilation)
43
+ })
44
+
45
+ // 等待普通资产写入完成后,再按配置顺序发布延迟资产。
46
+ compiler.hooks.afterEmit.tapPromise(PLUGIN_NAME, async compilation => {
47
+ try {
48
+ if (compilation.errors.length > 0) return
49
+ await this.flushDeferredOutputs(compilation)
50
+ } finally {
51
+ this.deferredOutputs.delete(compilation)
52
+ }
53
+ })
54
+ }
55
+
56
+ /**
57
+ * 代理原始 OutputFileSystem。
58
+ * 仅重写 writeFile,其余方法调用原始文件系统实现。
59
+ */
60
+ private createOutputFileSystem(compiler: Compiler, original: OutputFileSystem): OutputFileSystem {
61
+ return new Proxy(original, {
62
+ get: (target, property) => {
63
+ if (property === 'writeFile') return this.createWriteFile(compiler, original)
64
+ const value = Reflect.get(target, property, target)
65
+ return typeof value === 'function' ? value.bind(target) : value
66
+ }
67
+ })
68
+ }
69
+
70
+ /**
71
+ * 创建自定义 writeFile 实现。
72
+ */
73
+ private createWriteFile(compiler: Compiler, original: OutputFileSystem): WriteFile {
74
+ const originalWriteFile = original.writeFile.bind(original)
75
+
76
+ return (file: PathOrFileDescriptor, data: WriteFileData, optionsOrCallback: WriteFileOptions | NoParamCallback, optionalCallback?: NoParamCallback): void => {
77
+
78
+ const callback = (() => {
79
+ if (typeof optionsOrCallback === 'function') return optionsOrCallback
80
+ return optionalCallback
81
+ })()
82
+
83
+ const triggerOriginalWriteFile = () => {
84
+ if (typeof optionsOrCallback === 'function') return originalWriteFile(file, data, optionsOrCallback)
85
+ if (optionalCallback) originalWriteFile(file, data, optionsOrCallback, optionalCallback)
86
+ }
87
+
88
+ if (typeof file !== 'string' || !callback) return triggerOriginalWriteFile()
89
+
90
+ const assetName = this.getAssetName(compiler, file)
91
+
92
+ if (assetName && this.deferredAssets.includes(assetName)) return callback(null)
93
+
94
+ this.writeFileAtomically(file, data).then(() => callback(null)).catch(error => callback(error))
95
+ }
96
+ }
97
+
98
+ private collectDeferredOutputs(compiler: Compiler, compilation: Compilation): void {
99
+ if (this.deferredAssets.length === 0) return
100
+
101
+ const {path: outputPath} = compiler.options.output
102
+
103
+ if (!outputPath) throw new Error(`[${PLUGIN_NAME}] 无法收集延迟资产:output.path 未配置`)
104
+
105
+ const outputs = new Map<string, DeferredOutput>()
106
+
107
+ this.deferredAssets.forEach(assetName => {
108
+ const asset = compilation.getAsset(assetName)
109
+ if (!asset) return
110
+ const data = asset.source.source()
111
+ outputs.set(assetName, {data, file: path.join(outputPath, assetName)})
112
+ })
113
+
114
+ this.deferredOutputs.set(compilation, outputs)
115
+ }
116
+
117
+ private getAssetName(compiler: Compiler, file: string) {
118
+ const {path: outputPath} = compiler.options.output
119
+
120
+ if (!outputPath) return
121
+
122
+ const assetName = path.relative(outputPath, file).replaceAll('\\', '/')
123
+
124
+ if (assetName.startsWith('../') || path.isAbsolute(assetName)) return
125
+
126
+ return assetName
127
+ }
128
+
129
+ private async flushDeferredOutputs(compilation: Compilation) {
130
+ const outputs = this.deferredOutputs.get(compilation)
131
+
132
+ if (!outputs) return
133
+
134
+ return Promise.all(this.deferredAssets.map(assetName => {
135
+ const output = outputs.get(assetName)
136
+ if (!output) return
137
+ return this.writeFileAtomically(output.file, output.data)
138
+ }))
139
+ }
140
+
141
+ /**
142
+ * 通过同目录临时文件和 rename 原子替换目标文件。
143
+ */
144
+ private async writeFileAtomically(targetPath: string, data: WriteFileData): Promise<void> {
145
+ const directory = path.dirname(targetPath)
146
+
147
+ const temporaryPath = path.join(directory, `.${path.basename(targetPath)}.${randomUUID()}.tmp`)
148
+
149
+ await mkdir(directory, {recursive: true})
150
+
151
+ try {
152
+ await writeFile(temporaryPath, data)
153
+ await rename(temporaryPath, targetPath)
154
+ } finally {
155
+ await rm(temporaryPath, {force: true})
156
+ }
157
+ }
158
+ }
@@ -0,0 +1,70 @@
1
+ import type {Compilation, Compiler} from 'webpack'
2
+ import {RawSource} from 'webpack-sources'
3
+
4
+ export interface HmrStylePluginOptions {
5
+ /** Webpack/Taro 生成的全局样式资产。 */
6
+ sourceAsset: string
7
+ /** 固定入口资产;后续编译持续引用 patchAsset。 */
8
+ entryAsset: string
9
+ /** 每轮热编译输出的独立样式资产。 */
10
+ patchAsset: string
11
+ /** 是否将入口固定为对 patchAsset 的导入。 */
12
+ preserveEntry?: boolean
13
+ /** 自定义源样式到 patch 样式的内容转换。 */
14
+ transform?: (source: string, compilation: Compilation) => string
15
+ }
16
+
17
+ const PLUGIN_NAME = 'HmrStylePlugin'
18
+
19
+ /**
20
+ * 将构建器生成的全局样式复制到独立 HMR 资产,并可固定入口文件。
21
+ * 应在构建器完成最终资产变换后运行。
22
+ */
23
+ export class HmrStylePlugin {
24
+ private readonly options: HmrStylePluginOptions
25
+
26
+ private initialBuildDone = false
27
+
28
+ constructor(options: HmrStylePluginOptions) {
29
+ this.options = options
30
+ }
31
+
32
+ apply(compiler: Compiler) {
33
+ compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
34
+ const stage = compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT
35
+ compilation.hooks.processAssets.tap({name: PLUGIN_NAME, stage}, () => this.processAssets(compilation))
36
+ })
37
+
38
+ compiler.hooks.afterEmit.tap(PLUGIN_NAME, compilation => {
39
+ if (compilation.errors.length === 0 && compilation.hash) this.initialBuildDone = true
40
+ })
41
+
42
+ compiler.hooks.watchClose.tap(PLUGIN_NAME, () => {
43
+ this.initialBuildDone = false
44
+ })
45
+ }
46
+
47
+ private processAssets(compilation: Compilation) {
48
+ if (!compilation.hash || compilation.errors.length > 0) return
49
+
50
+ const {sourceAsset, entryAsset, patchAsset, preserveEntry = true, transform} = this.options
51
+ const source = compilation.getAsset(sourceAsset)?.source.source().toString()
52
+
53
+ if (source !== undefined) {
54
+ const patchSource = transform ? transform(source, compilation) : source
55
+ this.updateAsset(compilation, patchAsset, new RawSource(patchSource), {
56
+ hotModuleReplacement: this.initialBuildDone
57
+ })
58
+ }
59
+
60
+ if (preserveEntry) {
61
+ const entry = new RawSource(`@import ${JSON.stringify(`./${patchAsset}`)};\n`)
62
+ this.updateAsset(compilation, entryAsset, entry)
63
+ }
64
+ }
65
+
66
+ private updateAsset(compilation: Compilation, name: string, source: RawSource, info = {}) {
67
+ if (compilation.getAsset(name)) compilation.updateAsset(name, source, info)
68
+ else compilation.emitAsset(name, source, info)
69
+ }
70
+ }
@@ -3,22 +3,25 @@ import path from "path";
3
3
  import {getAllPages} from '../utils'
4
4
  import {isPageCompiled} from './compile-state'
5
5
  import type {AppConfig} from "@tarojs/taro";
6
+ import generator from '@babel/generator'
7
+ import {parse} from '@babel/parser'
8
+ import template from '@babel/template'
9
+ import traverse from '@babel/traverse'
10
+ import * as t from '@babel/types'
6
11
 
7
12
 
8
13
  interface CreateShellOpt {
9
14
  page: string
10
15
  framework: 'react'
11
16
  compileUrl: string
12
- memo: boolean
13
17
  }
14
18
 
15
19
  export const createReactShell = (opt: CreateShellOpt) => {
16
- const {page, compileUrl, memo} = opt
20
+ const {page, compileUrl} = opt
17
21
  return `
18
22
  import { PageShell } from ${JSON.stringify(require.resolve('@taro-hmr-compile/core/runtime'))}
19
- ${memo ? "import React from 'react'" : ''}
20
23
  const Page = () => <PageShell page={${JSON.stringify(page)}} compileUrl={${JSON.stringify(compileUrl)}}/>
21
- export default ${memo ? 'React.memo(Page)' : 'Page'}
24
+ export default Page
22
25
  `
23
26
  }
24
27
 
@@ -27,8 +30,69 @@ const createShell = (opt: CreateShellOpt) => {
27
30
  throw new Error(`unsupported framework: ${opt.framework}`)
28
31
  }
29
32
 
30
- const isMemoPage = (source: string) => {
31
- return /\bexport\s+default\s+(?:(?:React\.)?memo|observer)\s*\(/.test(source)
33
+ export const wrapReactPage = (source: string, pageName: string): string => {
34
+ const ast = parse(source, {sourceType: 'module', plugins: ['typescript', 'jsx']})
35
+ const runtimeRequest = require.resolve('@taro-hmr-compile/core/runtime')
36
+
37
+ traverse(ast, {
38
+ Program(programPath) {
39
+ const hasWithHmrPage = () => programPath.node.body.some(node => {
40
+ if (!t.isImportDeclaration(node) || node.source.value !== runtimeRequest) return false
41
+
42
+ return node.specifiers.some(specifier => {
43
+ return t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {name: 'withHmrPage'})
44
+ })
45
+ })
46
+
47
+ if (hasWithHmrPage()) return
48
+
49
+ const withHmrPage = programPath.scope.generateUidIdentifier('withHmrPage')
50
+
51
+ programPath.traverse({
52
+ ExportDefaultDeclaration(exportPath) {
53
+ if (hasWithHmrPage()) return
54
+ const declaration = exportPath.node.declaration
55
+
56
+ // 跳过只有类型声明、没有函数实现 的 TypeScript 节点
57
+ if (t.isTSDeclareFunction(declaration)) return
58
+
59
+ const component = (() => {
60
+ // 具名函数或类保留原声明,通过名称引用,避免破坏模块内的其他引用。
61
+ if ((t.isFunctionDeclaration(declaration) || t.isClassDeclaration(declaration)) && declaration.id) return t.identifier(declaration.id.name)
62
+
63
+ // 标识符、箭头函数、observer(...) 等表达式可以直接作为包装参数。
64
+ if (t.isExpression(declaration)) return declaration
65
+
66
+ // 匿名函数或类声明需要先转成表达式,才能作为包装参数。
67
+ return t.toExpression(declaration)
68
+ })()
69
+ const defaultExport = template.statement(`export default %%WRAPPER%%(%%COMPONENT%%, %%PAGE_NAME%%);`)({
70
+ WRAPPER: withHmrPage,
71
+ COMPONENT: component,
72
+ PAGE_NAME: t.stringLiteral(pageName),
73
+ })
74
+
75
+ const hasNamedDeclaration = (t.isFunctionDeclaration(declaration) || t.isClassDeclaration(declaration)) && Boolean(declaration.id)
76
+
77
+ // 先插入 runtime 导入,让替换后重新入队的默认导出也能识别为已处理。
78
+ programPath.unshiftContainer('body', template.statement(`import { withHmrPage as %%WRAPPER%% } from %%RUNTIME%%;`)({
79
+ WRAPPER: withHmrPage,
80
+ RUNTIME: t.stringLiteral(runtimeRequest),
81
+ }))
82
+
83
+ // 具名函数或类保留声明,再追加包装后的默认导出。
84
+ if (hasNamedDeclaration) exportPath.replaceWithMultiple([declaration, defaultExport])
85
+
86
+ // 表达式或匿名声明直接替换为包装后的默认导出。
87
+ if (!hasNamedDeclaration) exportPath.replaceWith(defaultExport)
88
+
89
+ exportPath.skip()
90
+ },
91
+ })
92
+ },
93
+ })
94
+
95
+ return generator(ast).code
32
96
  }
33
97
 
34
98
 
@@ -38,20 +102,31 @@ interface LoaderOptions {
38
102
  appConfig: AppConfig
39
103
  framework: 'react'
40
104
  compileUrl: string
105
+ lazyCompileExclude?: string[]
41
106
  }
42
107
 
43
108
  const lazyCompilerLoader: LoaderDefinitionFunction<LoaderOptions> = function (source) {
44
- const {appPath, framework, appConfig, sourcePath, compileUrl} = this.getOptions()
109
+ const {appPath, framework, appConfig, sourcePath, compileUrl, lazyCompileExclude = []} = this.getOptions()
45
110
 
46
111
  const {dir: resourceDir, name: resourceName} = path.parse(path.relative(sourcePath, this.resourcePath))
47
112
 
48
- const resourcePath = path.join(resourceDir, resourceName)
113
+ const resourcePath = path.join(resourceDir, resourceName).replace(/\\/g, '/')
49
114
 
50
115
  const isPageEntry = getAllPages(appConfig).includes(resourcePath)
51
116
 
52
- if (!isPageEntry || isPageCompiled(appPath, resourcePath)) return source
117
+ if (!isPageEntry) return source
118
+
119
+ if (isPageCompiled(appPath, resourcePath)) return wrapReactPage(source, resourcePath)
120
+
121
+ const isExcluded = lazyCompileExclude.some(excludePath => {
122
+ if (!excludePath) return false
123
+ const normalizedPath = path.posix.normalize(excludePath.replace(/\\/g, '/')).replace(/^\/+/, '')
124
+ return normalizedPath.endsWith('/') ? resourcePath.startsWith(normalizedPath) : resourcePath === normalizedPath
125
+ })
126
+
127
+ if (isExcluded) return wrapReactPage(source, resourcePath)
53
128
 
54
- return createShell({page: resourcePath, framework, compileUrl, memo: isMemoPage(source)})
129
+ return createShell({page: resourcePath, framework, compileUrl})
55
130
  }
56
131
 
57
132
  export default lazyCompilerLoader
package/src/constants.ts CHANGED
@@ -2,6 +2,8 @@ export const HMR_OUTPUT_PATH = 'hmr'
2
2
 
3
3
  export const HMR_PATCH_ASSET = `${HMR_OUTPUT_PATH}/patch.js`
4
4
 
5
+ export const HMR_PATCH_STYLE_ASSET = `${HMR_OUTPUT_PATH}/patch.wxss`
6
+
5
7
  export const DEFAULT_HMR_PATCH_HISTORY_LIMIT = 20
6
8
 
7
9
  export const DEFAULT_DEBUG_NAMESPACES = 'taro-hmr-compile:*'
package/src/index.ts CHANGED
@@ -1,25 +1,29 @@
1
1
  import type {IPluginContext} from '@tarojs/service'
2
2
  import type {AppConfig} from '@tarojs/taro'
3
- import {HMR_OUTPUT_PATH, DEFAULT_DEBUG_NAMESPACES} from './constants'
3
+ import {HMR_OUTPUT_PATH, HMR_PATCH_ASSET, HMR_PATCH_STYLE_ASSET, DEFAULT_DEBUG_NAMESPACES} from './constants'
4
4
  import {getAppConfig} from './utils'
5
5
  import {HmrCompilerPlugin} from './compile/hmr-compiler-plugin'
6
6
  import {HmrPatchPlugin} from './patch/hmr-patch-plugin'
7
7
  import {HmrServerPlugin} from './server/hmr-server-plugin'
8
- import {emptyDirFile, findAvailablePort} from '@taro-hmr-compile/core/compiler'
8
+ import {findAvailablePort} from '@taro-hmr-compile/core/compiler'
9
+ import {HmrOutputPlugin} from './compile/hmr-output-plugin'
9
10
  import {enableLog} from './log'
10
11
 
12
+ const CUSTOM_WRAPPER = 'custom-wrapper'
11
13
 
12
14
  export interface WebpackHmrCompileOpt {
13
15
  host: string
14
16
  port: number
15
17
  patchHistoryLimit: number
16
18
  debug: boolean | string
19
+ /** 相对于 sourceRoot 的页面路径(不含扩展名),支持开头 /,末尾 / 表示目录。 */
20
+ lazyCompileExclude: string[]
17
21
  }
18
22
 
19
23
  export default (ctx: IPluginContext, pluginOpts: Partial<WebpackHmrCompileOpt>) => {
20
24
  if (!ctx.runOpts.options?.isWatch) return
21
25
 
22
- const {appPath, sourcePath, outputPath} = ctx.paths
26
+ const {appPath, sourcePath} = ctx.paths
23
27
 
24
28
  const {framework} = ctx.initialConfig
25
29
 
@@ -36,7 +40,10 @@ export default (ctx: IPluginContext, pluginOpts: Partial<WebpackHmrCompileOpt>)
36
40
 
37
41
  if (debugNamespaces) enableLog(debugNamespaces)
38
42
 
39
- ctx.onBuildStart(() => emptyDirFile(outputPath))
43
+ ctx.modifyComponentConfig(({componentConfig}) => {
44
+ if (componentConfig.thirdPartyComponents.has(CUSTOM_WRAPPER)) return
45
+ componentConfig.thirdPartyComponents.set(CUSTOM_WRAPPER, new Set())
46
+ })
40
47
 
41
48
  ctx.modifyRunnerOpts(({opts}) => {
42
49
  opts.output ??= {}
@@ -59,7 +66,7 @@ export default (ctx: IPluginContext, pluginOpts: Partial<WebpackHmrCompileOpt>)
59
66
  .end()
60
67
  .use('lazy-compiler-loader')
61
68
  .loader(require.resolve('./compile/lazy-compiler-loader'))
62
- .options({appPath, sourcePath, appConfig, framework, compileUrl})
69
+ .options({appPath, sourcePath, appConfig, framework, compileUrl, lazyCompileExclude: pluginOpts.lazyCompileExclude})
63
70
  .end()
64
71
 
65
72
  chain.output
@@ -68,12 +75,17 @@ export default (ctx: IPluginContext, pluginOpts: Partial<WebpackHmrCompileOpt>)
68
75
 
69
76
  const {patchHistoryLimit} = pluginOpts
70
77
 
71
- const [{filename: styleFilename}] = chain.plugin('miniCssExtractPlugin')?.get('args') || []
72
-
73
- chain.plugin('hmr-compiler-plugin').use(HmrCompilerPlugin, [{paths: ctx.paths, appConfig, styleFilename, debugNamespaces}])
74
-
78
+ chain.plugin('hmr-compiler-plugin').use(HmrCompilerPlugin, [{
79
+ paths: ctx.paths,
80
+ appConfig,
81
+ debugNamespaces
82
+ }])
75
83
  chain.plugin('hmr-plugin').use(webpack.HotModuleReplacementPlugin)
76
84
 
85
+ chain.plugin('hmr-output-plugin').use(HmrOutputPlugin, [{
86
+ deferredAssets: [HMR_PATCH_STYLE_ASSET, HMR_PATCH_ASSET, 'app.wxss'],
87
+ }])
88
+
77
89
  chain.plugin('hmr-patch-plugin').use(HmrPatchPlugin, [{patchHistoryLimit}])
78
90
 
79
91
  chain.plugin('hmr-server-plugin').use(HmrServerPlugin, [{host, port}])
@@ -1,6 +1,7 @@
1
1
  import type {Compilation, Compiler} from 'webpack'
2
2
  import {RawSource} from 'webpack-sources'
3
- import {HMR_PATCH_ASSET} from '../constants'
3
+ import path from 'node:path'
4
+ import {HMR_PATCH_ASSET, HMR_PATCH_STYLE_ASSET} from '../constants'
4
5
  import {HmrCompilerPlugin} from '../compile/hmr-compiler-plugin'
5
6
  import {HmrPatchRuntimePlugin} from './hmr-patch-runtime-plugin'
6
7
  import {HmrPatchProcessor, HmrPatchProcessorOptions} from "./hmr-patch-processor";
@@ -10,6 +11,7 @@ const HOT_UPDATE_MANIFEST_SUFFIX = '.hot-update.json'
10
11
  const HOT_UPDATE_SCRIPT_SUFFIX = '.hot-update.js'
11
12
  const STYLE_ASSET_PATTERN = /\.(?:css|wxss|acss|ttss|qss|jxss)(?:\.map)?$/i
12
13
  const TEMPLATE_RUNTIME_ASSET_PATTERN = /(?:^|\/)(?:base\.wxml|utils\.wxs)$/i
14
+ const STYLE_ENTRY_ASSET = 'app.wxss'
13
15
 
14
16
  type HmrPatchPluginOptions = Partial<HmrPatchProcessorOptions>
15
17
 
@@ -25,6 +27,8 @@ export class HmrPatchPlugin {
25
27
 
26
28
  private readonly patchProcessor: HmrPatchProcessor
27
29
 
30
+ private readonly preservedAssets = new Set([HMR_PATCH_ASSET, STYLE_ENTRY_ASSET, HMR_PATCH_STYLE_ASSET])
31
+
28
32
  private readonly emittedAssetSources = new Map<string, string>()
29
33
 
30
34
  constructor(options: HmrPatchPluginOptions) {
@@ -35,13 +39,18 @@ export class HmrPatchPlugin {
35
39
  new HmrPatchRuntimePlugin().apply(compiler)
36
40
 
37
41
  compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
38
- HmrCompilerPlugin.getCompilationHooks(compilation).chunkModulesRendered.tap(PLUGIN_NAME, (source, isBootstrapChunk) => {
39
- this.patchProcessor.processChunkModules({compilation, source, isBootstrapChunk})
42
+ HmrCompilerPlugin.getCompilationHooks(compilation).chunkModulesRendered.tap(PLUGIN_NAME, options => {
43
+ this.patchProcessor.processChunkModules({compilation, ...options})
40
44
  })
41
45
 
42
46
  // 等 Webpack 生成完整的 hot-update assets 后,再统一转换成固定的 patch.js。
43
47
  const stage = compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT
44
- compilation.hooks.processAssets.tap({name: PLUGIN_NAME, stage}, () => this.processAssets(compilation))
48
+ compilation.hooks.processAssets.tap({name: PLUGIN_NAME, stage}, () => {
49
+ if (compilation.errors.length > 0 || !compilation.hash) return
50
+ this.processStyleAssets(compilation)
51
+ this.processAssets(compilation)
52
+ })
53
+ this.removeHotUpdateAssets(compilation)
45
54
  })
46
55
 
47
56
  compiler.hooks.afterEmit.tap(PLUGIN_NAME, compilation => {
@@ -82,10 +91,40 @@ export class HmrPatchPlugin {
82
91
  this.previousHash = toHash
83
92
  }
84
93
 
94
+ /** 将 Webpack 汇总后的 App 样式放入固定 patch 文件,App 入口只保留稳定引用。 */
95
+ private processStyleAssets(compilation: Compilation) {
96
+ const entryAsset = compilation.getAsset(STYLE_ENTRY_ASSET)
97
+ const source = entryAsset?.source.source().toString()
98
+ if (!source) return
99
+
100
+ const importPath = path.posix.relative(path.posix.dirname(STYLE_ENTRY_ASSET), HMR_PATCH_STYLE_ASSET)
101
+ const patchImport = importPath.startsWith('.') ? importPath : `./${importPath}`
102
+ const alreadyPatched = source.trim() === `@import "${patchImport}";` || source.trim() === `@import '${patchImport}';`
103
+
104
+ if (!alreadyPatched) {
105
+ const patchDirectory = path.posix.dirname(HMR_PATCH_STYLE_ASSET)
106
+ const sourceDirectory = path.posix.dirname(STYLE_ENTRY_ASSET)
107
+ const patchSource = source.replace(/(@import\s+)(["'])([^"']+)\2/g, (match, prefix: string, quote: string, request: string) => {
108
+ if (/^(?:[a-z]+:|\/|#)/i.test(request)) return match
109
+ const resolved = path.posix.normalize(path.posix.join(sourceDirectory, request))
110
+ const relative = path.posix.relative(patchDirectory, resolved)
111
+ return `${prefix}${quote}${relative.startsWith('.') ? relative : `./${relative}`}${quote}`
112
+ })
113
+ this.emitAsset(compilation, HMR_PATCH_STYLE_ASSET, new RawSource(patchSource))
114
+ }
115
+
116
+ this.emitAsset(compilation, STYLE_ENTRY_ASSET, new RawSource(`@import ${JSON.stringify(patchImport)};\n`))
117
+ }
118
+
119
+ private emitAsset(compilation: Compilation, assetName: string, source: RawSource) {
120
+ if (compilation.getAsset(assetName)) compilation.updateAsset(assetName, source)
121
+ else compilation.emitAsset(assetName, source)
122
+ }
123
+
85
124
  /** 热更新转换完成后,保留固定 patch 与发生变化的模板、平台样式资产。 */
86
125
  private removeSupersededAssets(compilation: Compilation) {
87
126
  compilation.getAssets().forEach(asset => {
88
- if (asset.name === HMR_PATCH_ASSET) return
127
+ if (this.preservedAssets.has(asset.name)) return
89
128
  if (!isPassthroughAsset(asset.name)) return compilation.deleteAsset(asset.name)
90
129
 
91
130
  const source = asset.source.source().toString()
@@ -108,4 +147,13 @@ export class HmrPatchPlugin {
108
147
  this.emittedAssetSources.clear()
109
148
  this.patchProcessor.reset()
110
149
  }
150
+ /** 补丁已从 hot-update assets 生成后,在 Webpack 写盘前从本次 compilation 移除它们。 */
151
+ private removeHotUpdateAssets(compilation: Compilation) {
152
+ compilation.getAssets().forEach(asset => {
153
+ if (asset.name.endsWith(HOT_UPDATE_MANIFEST_SUFFIX) || asset.name.endsWith(HOT_UPDATE_SCRIPT_SUFFIX)) {
154
+ compilation.deleteAsset(asset.name)
155
+ }
156
+ })
157
+ }
158
+
111
159
  }