vite-plugin-taro 0.0.3 → 0.0.4

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.
@@ -0,0 +1,230 @@
1
+ import type { types as BabelTypes, NodePath, PluginObj } from '@babel/core'
2
+ import babel from '@rolldown/plugin-babel'
3
+ import react from '@vitejs/plugin-react'
4
+ import type { HtmlTagDescriptor, PluginOption, UserConfig } from 'vite'
5
+ import { isProd, nodeRequire } from '../constants.ts'
6
+ import type { JsonObject, VitePluginTaroBuildContext, VitePluginTaroPageOption } from '../types.ts'
7
+ import { createPageComponentImport } from '../utils.ts'
8
+
9
+ const virtualH5Id = 'virtual:vite-plugin-taro/h5'
10
+ const patchStencilCssOrder = true
11
+
12
+ /**
13
+ * Checks whether an id belongs to an H5 virtual module.
14
+ */
15
+ export function isH5VirtualModuleId(id: string): boolean {
16
+ return id === virtualH5Id
17
+ }
18
+
19
+ /**
20
+ * Loads generated source for H5 virtual modules.
21
+ */
22
+ export function loadH5VirtualModule(cleanId: string, context: VitePluginTaroBuildContext): string | undefined {
23
+ if (cleanId !== virtualH5Id) return
24
+ return createWebEntry(context)
25
+ }
26
+
27
+ /**
28
+ * Configures the Vite pieces needed for Taro H5 resolve/runtime behavior.
29
+ */
30
+ export function createH5ViteConfig(): UserConfig {
31
+ return {
32
+ define: createH5TaroDefines(),
33
+ resolve: {
34
+ mainFields: ['main:h5', 'browser', 'module', 'jsnext:main', 'jsnext'],
35
+ alias: [
36
+ // Resolve Stencil's transitive runtime import after Taro components are optimized separately.
37
+ ...(patchStencilCssOrder
38
+ ? [
39
+ {
40
+ find: /^@stencil\/core\/internal\/client$/,
41
+ replacement: nodeRequire.resolve('@stencil/core/internal/client', {
42
+ paths: [nodeRequire.resolve('@tarojs/components/package.json')]
43
+ })
44
+ }
45
+ ]
46
+ : []),
47
+ // H5 React code must use Taro's React component wrappers, not the raw custom-element entry.
48
+ { find: /^@tarojs\/components$/, replacement: nodeRequire.resolve('@tarojs/components/lib/react') },
49
+ // Taro's H5 router/components deep-import this custom-element loader; make it resolvable under pnpm.
50
+ {
51
+ find: /^@tarojs\/components\/dist\/components$/,
52
+ replacement: nodeRequire.resolve('@tarojs/components/dist/components')
53
+ },
54
+ // H5 APIs are exported from the platform API barrel; the generic @tarojs/taro root is native-oriented.
55
+ {
56
+ find: /^@tarojs\/taro$/,
57
+ replacement: nodeRequire.resolve('@tarojs/plugin-platform-h5/dist/runtime/apis')
58
+ }
59
+ ]
60
+ },
61
+ optimizeDeps: {
62
+ // Keep the Stencil runtime in Vite's transform pipeline so rewriteStencilStyleInsertion can patch it.
63
+ exclude: [patchStencilCssOrder ? '@stencil/core/internal/client' : ''].filter(Boolean)
64
+ },
65
+ build: {
66
+ target: 'es2018',
67
+ minify: isProd
68
+ }
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Creates H5-only support plugins used before the target emitter runs.
74
+ *
75
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-platform-h5/src/program.ts#L219-L249
76
+ */
77
+ export function createH5SupportPlugins(): PluginOption[] {
78
+ const plugins: PluginOption[] = [...react()]
79
+
80
+ if (patchStencilCssOrder) {
81
+ plugins.push(
82
+ babel({
83
+ include: /[\\/]@stencil[\\/]core[\\/]internal[\\/]client[\\/]index\.js(?:\?.*)?$/,
84
+ exclude: [],
85
+ plugins: [rewriteStencilStyleInsertion]
86
+ })
87
+ )
88
+ }
89
+
90
+ // Mirrors Taro H5: rewrite default Taro.xxx calls from vite-plugin-taro/taro to named H5 API imports.
91
+ plugins.push(
92
+ babel({
93
+ plugins: [
94
+ [
95
+ nodeRequire.resolve('babel-plugin-transform-taroapi'),
96
+ {
97
+ packageName: 'vite-plugin-taro/taro',
98
+ definition: nodeRequire(nodeRequire.resolve('@tarojs/plugin-platform-h5/dist/definition.json'))
99
+ }
100
+ ]
101
+ ]
102
+ })
103
+ )
104
+
105
+ return plugins
106
+ }
107
+
108
+ function rewriteStencilStyleInsertion(): PluginObj {
109
+ return {
110
+ name: 'rewrite-stencil-style-insertion',
111
+ visitor: {
112
+ CallExpression(path: NodePath<BabelTypes.CallExpression>) {
113
+ if (!isStencilStyleInsertBeforeCall(path)) return
114
+
115
+ path.get('arguments.1').replaceWithSourceString(
116
+ `scopeId.startsWith('sc-taro-') ? styleContainerNode.querySelector('style,link[rel="stylesheet"]') : styleContainerNode.querySelector('link')`
117
+ )
118
+ }
119
+ }
120
+ }
121
+ }
122
+
123
+ function isStencilStyleInsertBeforeCall(path: NodePath<BabelTypes.CallExpression>): boolean {
124
+ return (
125
+ path.get('callee').matchesPattern('styleContainerNode.insertBefore') &&
126
+ path.get('arguments.0').toString() === 'styleElm' &&
127
+ path.get('arguments.1').toString() === "styleContainerNode.querySelector('link')"
128
+ )
129
+ }
130
+
131
+ /**
132
+ * Creates compile-time constants expected by Taro's Web runtime packages.
133
+ *
134
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/webpack/H5WebpackPlugin.ts#L51-L69
135
+ */
136
+ function createH5TaroDefines(): Record<string, string> {
137
+ return {
138
+ 'process.env.FRAMEWORK': JSON.stringify('react'),
139
+ 'process.env.SUPPORT_TARO_POLYFILL': JSON.stringify('disabled'),
140
+ 'process.env.TARO_ENV': JSON.stringify('h5'),
141
+ 'process.env.TARO_PLATFORM': JSON.stringify('web'),
142
+ IS_H5: 'true',
143
+ IS_WEAPP: 'false',
144
+ 'process.env.SUPPORT_DINGTALK_NAVIGATE': JSON.stringify('disabled'),
145
+ DEPRECATED_ADAPTER_COMPONENT: 'false'
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Injects vite-plugin-taro's generated Web entry into Vite's HTML shell.
151
+ */
152
+ export function createWebIndexHtmlTags(context: VitePluginTaroBuildContext): HtmlTagDescriptor[] | undefined {
153
+ if (context.target !== 'h5') return
154
+
155
+ const tags: HtmlTagDescriptor[] = []
156
+ tags.push({
157
+ tag: 'script',
158
+ attrs: { type: 'module' },
159
+ children: `import '${virtualH5Id}'`,
160
+ injectTo: 'body'
161
+ })
162
+ return tags
163
+ }
164
+
165
+ /**
166
+ * Builds the generated Web entry around Taro's official Web router/runtime APIs.
167
+ * Base Taro CSS is imported before the app; component CSS order is handled by rewriteStencilStyleInsertion.
168
+ *
169
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-loader/src/h5.ts#L120-L150
170
+ */
171
+ export function createWebEntry(context: VitePluginTaroBuildContext): string {
172
+ const webAppConfigCode = JSON.stringify(createWebAppConfig(context.appConfig))
173
+ const webRoutesConfigCode = createWebRoutesConfig(context.pages)
174
+
175
+ return `import ${JSON.stringify(nodeRequire.resolve('@tarojs/components/global.css'))}
176
+ import ${JSON.stringify(nodeRequire.resolve('@tarojs/components/dist/taro-components/taro-components.css'))}
177
+ import {
178
+ createHashHistory,
179
+ createReactApp,
180
+ createRouter,
181
+ handleAppMount,
182
+ window
183
+ } from 'vite-plugin-taro/shim/h5'
184
+ import React from 'react'
185
+ import ReactDOM from 'react-dom/client'
186
+ import AppComponent from '${context.appComponentImport}'
187
+
188
+ const config = window.__taroAppConfig = ${webAppConfigCode}
189
+ config.routes = ${webRoutesConfigCode}
190
+ const app = createReactApp(AppComponent, React, ReactDOM, config)
191
+ const history = createHashHistory({ window })
192
+ handleAppMount(config, history)
193
+ createRouter(history, app, config, React)
194
+ `
195
+ }
196
+
197
+ /**
198
+ * Creates the H5 app config consumed by Taro's Web router.
199
+ * Taro's H5 runtime expects `config.router` to exist, even when it is an empty object.
200
+ *
201
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/plugins/H5Plugin.ts#L49-L53
202
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/plugins/H5Plugin.ts#L133-L138
203
+ */
204
+ function createWebAppConfig(sharedAppConfig: JsonObject): JsonObject {
205
+ return {
206
+ router: {},
207
+ ...sharedAppConfig
208
+ }
209
+ }
210
+
211
+ /**
212
+ * Creates Web route records in the same shape as Taro's H5 loader.
213
+ *
214
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-loader/src/h5.ts#L12-L21
215
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-loader/src/h5.ts#L108-L114
216
+ */
217
+ function createWebRoutesConfig(webPages: VitePluginTaroPageOption[]): string {
218
+ const webRoutes = webPages.map((page) =>
219
+ [
220
+ 'Object.assign({',
221
+ ` path: ${JSON.stringify(page.path)},`,
222
+ ' load: async function(context, params) {',
223
+ ` const page = await import(${JSON.stringify(createPageComponentImport(page.path))})`,
224
+ ' return [page, context, params]',
225
+ ' }',
226
+ `}, ${JSON.stringify(page.config)})`
227
+ ].join('\n')
228
+ )
229
+ return `[\n${webRoutes.join(',\n')}\n]`
230
+ }
@@ -0,0 +1,438 @@
1
+ import path from 'node:path'
2
+ import { recursiveMerge } from '@tarojs/helper'
3
+ import { Weapp as WechatPlatform } from '@tarojs/plugin-platform-weapp'
4
+ import type { UserConfig } from 'vite'
5
+ import { isProd, nodeRequire } from '../constants.ts'
6
+ import type { JsonObject, VitePluginTaroBuildContext, VitePluginTaroPageOption } from '../types.ts'
7
+ import { createPageComponentImport, normalizeModuleId } from '../utils.ts'
8
+
9
+ const virtualWxAppId = 'virtual:vite-plugin-taro/wx/app'
10
+ const virtualWxCompId = 'virtual:vite-plugin-taro/wx/comp'
11
+ const virtualWxPagePrefix = 'virtual:vite-plugin-taro/wx/page/'
12
+
13
+ /**
14
+ * Checks whether an id belongs to a wx virtual module.
15
+ */
16
+ export function isWxVirtualModuleId(id: string): boolean {
17
+ return id === virtualWxAppId || id === virtualWxCompId || id.startsWith(virtualWxPagePrefix)
18
+ }
19
+
20
+ export function loadWxVirtualModule(cleanId: string, context: VitePluginTaroBuildContext): string | undefined {
21
+ if (cleanId === virtualWxAppId) {
22
+ return createWxAppEntry(context)
23
+ }
24
+
25
+ if (cleanId === virtualWxCompId) {
26
+ return createWxCompEntry()
27
+ }
28
+
29
+ if (!cleanId.startsWith(virtualWxPagePrefix)) {
30
+ return
31
+ }
32
+
33
+ const pagePath = cleanId.slice(virtualWxPagePrefix.length)
34
+ const page = context.pages.find((candidate) => candidate.path === pagePath)
35
+ if (page) {
36
+ return createWxPageEntry(page)
37
+ }
38
+ }
39
+
40
+ const taroWechatComponentsReactPath = nodeRequire.resolve('@tarojs/plugin-platform-weapp/dist/components-react')
41
+ const vitePluginTaroSourcePath = normalizeModuleId(path.dirname(nodeRequire.resolve('vite-plugin-taro/vite')))
42
+ const taroVersion = String(nodeRequire('@tarojs/runtime/package.json').version)
43
+
44
+ /**
45
+ * Configures wx target entry, output, and chunk layout.
46
+ */
47
+ export function createWxViteConfig(context: VitePluginTaroBuildContext): UserConfig {
48
+ return {
49
+ define: createWechatTaroDefines(),
50
+ // https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/webpack/MiniCombination.ts#L22-L84
51
+ resolve: {
52
+ // https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/webpack/MiniBaseConfig.ts#L44-L73
53
+ alias: [{ find: /^@tarojs\/components$/, replacement: taroWechatComponentsReactPath }]
54
+ },
55
+ build: {
56
+ target: 'es2018',
57
+ assetsInlineLimit: 1024,
58
+ cssCodeSplit: false,
59
+ minify: isProd,
60
+ rolldownOptions: {
61
+ // Start from app; page/component chunks below mirror Taro Webpack's generated entries.
62
+ input: { app: virtualWxAppId },
63
+ experimental: {
64
+ // Rolldown's dev debug comments include virtual IDs like "\0virtual:...".
65
+ // WeChat DevTools can blank-screen on those NUL markers, so disable them at the source.
66
+ attachDebugInfo: 'none'
67
+ },
68
+ output: {
69
+ format: 'cjs',
70
+ entryFileNames: '[name].js',
71
+ assetFileNames: 'assets/[name][extname]',
72
+ chunkFileNames: createWechatChunkFileName,
73
+ strictExecutionOrder: true,
74
+ codeSplitting: {
75
+ includeDependenciesRecursively: false,
76
+ minSize: 0,
77
+ // https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/webpack/MiniCombination.ts#L96-L144
78
+ groups: [
79
+ { name: 'taro', test: isWxTaroChunkModule, priority: 100 },
80
+ { name: 'vendors', test: isNodeModule, priority: 10 },
81
+ { name: 'common', minShareCount: 2, minModuleSize: 1, priority: 1 }
82
+ ]
83
+ }
84
+ }
85
+ }
86
+ }
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Creates compile-time constants expected by Taro's WeChat runtime packages.
92
+ *
93
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/webpack/MiniWebpackPlugin.ts#L67-L94
94
+ */
95
+ function createWechatTaroDefines(): Record<string, string> {
96
+ return {
97
+ 'process.env.FRAMEWORK': JSON.stringify('react'),
98
+ 'process.env.SUPPORT_TARO_POLYFILL': JSON.stringify('disabled'),
99
+ 'process.env.TARO_ENV': JSON.stringify('weapp'),
100
+ 'process.env.TARO_PLATFORM': JSON.stringify('mini'),
101
+ 'process.env.TARO_VERSION': JSON.stringify(taroVersion),
102
+ IS_H5: 'false',
103
+ IS_WEAPP: 'true',
104
+ ENABLE_ADJACENT_HTML: 'false',
105
+ ENABLE_CLONE_NODE: 'false',
106
+ ENABLE_CONTAINS: 'false',
107
+ ENABLE_INNER_HTML: 'false',
108
+ ENABLE_MUTATION_OBSERVER: 'false',
109
+ ENABLE_SIZE_APIS: 'false',
110
+ ENABLE_TEMPLATE_CONTENT: 'false'
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Checks whether a module should live in the Taro/framework base chunk.
116
+ * vite-plugin-taro support modules are kept with Taro so pages do not duplicate runtime facades.
117
+ *
118
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/webpack/MiniCombination.ts#L141-L144
119
+ */
120
+ function isWxTaroChunkModule(id: string): boolean {
121
+ const normalizedId = normalizeModuleId(id)
122
+ return normalizedId.includes('/node_modules/@tarojs/') || normalizedId.startsWith(`${vitePluginTaroSourcePath}/`)
123
+ }
124
+
125
+ /**
126
+ * Names Rolldown's helper chunk like Taro webpack's runtime chunk.
127
+ *
128
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/webpack/MiniCombination.ts#L96-L103
129
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/webpack/MiniCombination.ts#L115-L117
130
+ */
131
+ function createWechatChunkFileName(chunkInfo: { name: string }): string {
132
+ return `${chunkInfo.name === 'rolldown-runtime' ? 'runtime' : chunkInfo.name}.js`
133
+ }
134
+
135
+ /**
136
+ * Checks whether a module is a third-party dependency chunk candidate.
137
+ *
138
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/webpack/MiniCombination.ts#L132-L139
139
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-helper/src/utils.ts#L32-L36
140
+ */
141
+ function isNodeModule(id: string): boolean {
142
+ return normalizeModuleId(id).includes('/node_modules/')
143
+ }
144
+
145
+ type WechatAssetSource = string | Uint8Array
146
+
147
+ type WechatBundleModule = {
148
+ renderedExports?: string[]
149
+ }
150
+
151
+ type WechatBundleItem = {
152
+ type: 'asset' | 'chunk'
153
+ source?: WechatAssetSource
154
+ modules?: Record<string, WechatBundleModule>
155
+ }
156
+
157
+ type WechatBundle = Record<string, WechatBundleItem>
158
+
159
+ type WechatTemplateComponentConfig = {
160
+ includes: Set<string>
161
+ exclude: Set<string>
162
+ thirdPartyComponents: Map<string, Set<string>>
163
+ includeAll: boolean
164
+ }
165
+
166
+ type WechatChunkEmitter = {
167
+ emitFile(chunk: { type: 'chunk'; id: string; fileName: string; implicitlyLoadedAfterOneOf: string[] }): string
168
+ }
169
+
170
+ type WechatAssetEmitter = {
171
+ emitFile(asset: { type: 'asset'; fileName: string; source: WechatAssetSource }): string
172
+ }
173
+
174
+ /**
175
+ * Emits page and component chunks like Taro Webpack's MiniPlugin generated entries.
176
+ *
177
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/plugins/MiniPlugin.ts#L228-L243
178
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/plugins/MiniPlugin.ts#L743-L777
179
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/plugins/TaroSingleEntryPlugin.ts#L18-L38
180
+ */
181
+ export function emitWechatImplicitChunksForVirtualApp(
182
+ emitter: WechatChunkEmitter,
183
+ context: VitePluginTaroBuildContext,
184
+ cleanId: string
185
+ ): void {
186
+ if (context.target !== 'wx' || cleanId !== virtualWxAppId) return
187
+
188
+ for (const page of context.pages) {
189
+ emitter.emitFile({
190
+ type: 'chunk',
191
+ id: `${virtualWxPagePrefix}${page.path}`,
192
+ fileName: `${page.path}.js`,
193
+ implicitlyLoadedAfterOneOf: [cleanId]
194
+ })
195
+ }
196
+ emitter.emitFile({
197
+ type: 'chunk',
198
+ id: virtualWxCompId,
199
+ fileName: 'comp.js',
200
+ implicitlyLoadedAfterOneOf: [cleanId]
201
+ })
202
+ }
203
+
204
+ /**
205
+ * Builds the generated WeChat app entry that registers Taro's React App config.
206
+ * vite-plugin-taro omits Taro's generated pxTransform initialization because styles are handled by Tailwind.
207
+ *
208
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-loader/src/app.ts#L54-L63
209
+ */
210
+ export function createWxAppEntry(context: VitePluginTaroBuildContext): string {
211
+ const wechatAppConfigCode = JSON.stringify(context.appConfig)
212
+
213
+ return `import { createReactApp, ReactDOM } from 'vite-plugin-taro/shim/wx'
214
+ import React from 'react'
215
+ import AppComponent from '${context.appComponentImport}'
216
+
217
+ const appConfig = ${wechatAppConfigCode}
218
+ App(createReactApp(AppComponent, React, ReactDOM, appConfig))
219
+ `
220
+ }
221
+
222
+ /**
223
+ * Builds a generated WeChat page entry that registers Taro's Page config.
224
+ *
225
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-loader/src/page.ts#L52-L78
226
+ */
227
+ export function createWxPageEntry(pageOption: VitePluginTaroPageOption): string {
228
+ const wechatPageConfigCode = JSON.stringify(pageOption.config)
229
+ const pageComponentImport = createPageComponentImport(pageOption.path)
230
+ return `import { createPageConfig } from 'vite-plugin-taro/shim/wx'
231
+ import PageComponent from '${pageComponentImport}'
232
+
233
+ const pageConfig = ${wechatPageConfigCode}
234
+ const taroPageConfig = createPageConfig(PageComponent, '${pageOption.path}', { root: { cn: [] } }, pageConfig)
235
+ if (PageComponent && PageComponent.behaviors) {
236
+ taroPageConfig.behaviors = (taroPageConfig.behaviors || []).concat(PageComponent.behaviors)
237
+ }
238
+ Page(taroPageConfig)
239
+ `
240
+ }
241
+
242
+ /**
243
+ * Builds the generated JS companion for comp.wxml/comp.json. Without it WeChat
244
+ * can load recursive markup, but it will not have Taro's properties or `eh` event
245
+ * dispatch method.
246
+ *
247
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/template/comp.ts#L1-L4
248
+ */
249
+ export function createWxCompEntry(): string {
250
+ return `import { createRecursiveComponentConfig } from 'vite-plugin-taro/shim/wx'
251
+
252
+ Component(createRecursiveComponentConfig())
253
+ `
254
+ }
255
+
256
+ /**
257
+ * Creates Taro-style Mini Program template/config/style companion files.
258
+ *
259
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-platform-weapp/src/program.ts#L33-L55
260
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/plugins/MiniPlugin.ts#L1198-L1311
261
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/plugins/MiniPlugin.ts#L1346-L1390
262
+ */
263
+ export function emitWechatAssets(
264
+ emitter: WechatAssetEmitter,
265
+ bundle: WechatBundle,
266
+ context: VitePluginTaroBuildContext
267
+ ): void {
268
+ if (context.target !== 'wx') return
269
+ for (const asset of createWechatAssets(bundle, context)) {
270
+ emitter.emitFile({ type: 'asset', fileName: asset.fileName, source: asset.source })
271
+ }
272
+ }
273
+
274
+ function createWechatAssets(
275
+ bundle: WechatBundle,
276
+ context: VitePluginTaroBuildContext
277
+ ): { fileName: string; source: WechatAssetSource }[] {
278
+ const builder = createWechatTemplateBuilder()
279
+
280
+ return [
281
+ { fileName: 'app.json', source: stringifyJsonAsset(context.appConfig) },
282
+ { fileName: 'app.wxss', source: collectWechatBundleWxss(bundle) },
283
+ { fileName: 'base.wxml', source: builder.buildTemplate(collectWechatTemplateComponentConfig(bundle)) },
284
+ { fileName: 'utils.wxs', source: builder.buildXScript() },
285
+ { fileName: 'comp.wxml', source: builder.buildBaseComponentTemplate('.wxml') },
286
+ { fileName: 'comp.json', source: stringifyJsonAsset(createWechatCompJson()) },
287
+ { fileName: 'project.config.json', source: stringifyJsonAsset(context.projectConfigJson) },
288
+ { fileName: 'sitemap.json', source: stringifyJsonAsset(context.sitemapJson) },
289
+ ...context.pages.flatMap((page) => [
290
+ {
291
+ fileName: `${page.path}.wxml`,
292
+ source: builder.buildPageTemplate(relativeWechatRootAssetFromPage(page.path, 'base.wxml'), {
293
+ content: page.config,
294
+ path: page.path
295
+ })
296
+ },
297
+ {
298
+ fileName: `${page.path}.json`,
299
+ source: stringifyJsonAsset({
300
+ ...page.config,
301
+ usingComponents: {
302
+ comp: relativeWechatRootAssetFromPage(page.path, 'comp')
303
+ }
304
+ })
305
+ },
306
+ { fileName: `${page.path}.wxss`, source: '' }
307
+ ])
308
+ ]
309
+ }
310
+
311
+ function createWechatTemplateBuilder() {
312
+ const wechatPlatform = new WechatPlatform(
313
+ { helper: { recursiveMerge }, modifyWebpackChain() {}, registerPlatform() {} },
314
+ {},
315
+ {}
316
+ )
317
+ wechatPlatform.modifyTemplate({})
318
+ return wechatPlatform.template
319
+ }
320
+
321
+ /**
322
+ * Computes a WeChat import path from a page file to a generated root asset.
323
+ *
324
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/plugins/MiniPlugin.ts#L1270-L1298
325
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-helper/src/utils.ts#L74-L88
326
+ */
327
+ function relativeWechatRootAssetFromPage(wechatPagePath: string, wechatRootAsset: string): string {
328
+ const wechatPageDir = path.posix.dirname(wechatPagePath)
329
+ const relativePath = path.posix.relative(wechatPageDir, wechatRootAsset)
330
+ return relativePath.startsWith('.') ? relativePath : `./${relativePath}`
331
+ }
332
+
333
+ /**
334
+ * Builds Taro's template component include config from official defaults plus
335
+ * the component exports that Rolldown kept in the @tarojs/components bundle.
336
+ *
337
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/utils/component.ts#L3-L8
338
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/plugins/TaroComponentsExportsPlugin.ts#L83-L124
339
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/plugins/TaroLoadChunksPlugin.ts#L165-L180
340
+ */
341
+ function collectWechatTemplateComponentConfig(bundle: WechatBundle): WechatTemplateComponentConfig {
342
+ const wechatComponentConfig: WechatTemplateComponentConfig = {
343
+ includes: new Set([
344
+ 'view',
345
+ 'catch-view',
346
+ 'static-view',
347
+ 'pure-view',
348
+ 'click-view',
349
+ 'scroll-view',
350
+ 'image',
351
+ 'static-image',
352
+ 'text',
353
+ 'static-text'
354
+ ]),
355
+ exclude: new Set(),
356
+ thirdPartyComponents: new Map(),
357
+ includeAll: false
358
+ }
359
+
360
+ const wechatComponentsModule = findBundleModule(bundle, taroWechatComponentsReactPath)
361
+ for (const item of wechatComponentsModule?.renderedExports ?? []) {
362
+ wechatComponentConfig.includes.add(toDashed(item))
363
+ }
364
+
365
+ return wechatComponentConfig
366
+ }
367
+
368
+ function toDashed(s: string) {
369
+ return s.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()
370
+ }
371
+
372
+ /**
373
+ * Finds a module record inside the generated bundle by normalized module ID.
374
+ *
375
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/plugins/TaroComponentsExportsPlugin.ts#L83-L124
376
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/plugins/TaroLoadChunksPlugin.ts#L165-L180
377
+ */
378
+ function findBundleModule(bundle: WechatBundle, resolvedId: string): WechatBundleModule | undefined {
379
+ const normalizedResolvedId = normalizeModuleId(resolvedId)
380
+ for (const item of Object.values(bundle)) {
381
+ if (item.type !== 'chunk') {
382
+ continue
383
+ }
384
+
385
+ const found = Object.entries(item.modules ?? {}).find(([id]) => normalizeModuleId(id) === normalizedResolvedId)
386
+ if (found) {
387
+ return found[1]
388
+ }
389
+ }
390
+ }
391
+
392
+ /**
393
+ * Creates the JSON config for Taro's shared recursive component.
394
+ *
395
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/plugins/MiniPlugin.ts#L1228-L1252
396
+ */
397
+ function createWechatCompJson(): JsonObject {
398
+ return {
399
+ component: true,
400
+ styleIsolation: 'apply-shared',
401
+ // Taro's recursive template can nest <comp />, so the component references
402
+ // itself just like the official runner output.
403
+ usingComponents: { comp: './comp' }
404
+ }
405
+ }
406
+
407
+ /**
408
+ * Converts a WeChat-emitted asset's source into text.
409
+ */
410
+ function getWechatAssetSource(item: WechatBundleItem): string {
411
+ if (typeof item.source === 'string') return item.source
412
+ return item.source ? new TextDecoder().decode(item.source) : ''
413
+ }
414
+
415
+ /**
416
+ * Flattens Vite-emitted CSS into app.wxss and removes the intermediate CSS asset.
417
+ * This is vite-plugin-taro's Vite equivalent of Taro Webpack's app/common style consolidation.
418
+ *
419
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/plugins/MiniPlugin.ts#L1310-L1311
420
+ * https://github.com/NervJS/taro/blob/f0e5c39d5f04290db975670411e23c3a396e15f8/packages/taro-webpack5-runner/src/plugins/MiniPlugin.ts#L1471-L1528
421
+ */
422
+ function collectWechatBundleWxss(bundle: WechatBundle): string {
423
+ const wechatWxssChunks: string[] = []
424
+ for (const [fileName, item] of Object.entries(bundle)) {
425
+ if (item.type !== 'asset' || !fileName.endsWith('.css')) continue
426
+ const source = getWechatAssetSource(item)
427
+ if (source) wechatWxssChunks.push(source)
428
+ delete bundle[fileName]
429
+ }
430
+ return wechatWxssChunks.join('\n')
431
+ }
432
+
433
+ /**
434
+ * Serializes generated Mini Program JSON assets; vite-plugin-taro pretty-prints non-prod output.
435
+ */
436
+ function stringifyJsonAsset(value: JsonObject): string {
437
+ return isProd ? JSON.stringify(value) : JSON.stringify(value, null, 2)
438
+ }