@tarojs/plugin-framework-react 3.8.0-canary.0 → 4.0.0-alpha.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.
package/dist/index.js CHANGED
@@ -10,25 +10,137 @@ var walk = require('acorn-walk');
10
10
  var path = require('node:path');
11
11
 
12
12
  function _interopNamespaceDefault(e) {
13
- var n = Object.create(null);
14
- if (e) {
15
- Object.keys(e).forEach(function (k) {
16
- if (k !== 'default') {
17
- var d = Object.getOwnPropertyDescriptor(e, k);
18
- Object.defineProperty(n, k, d.get ? d : {
19
- enumerable: true,
20
- get: function () { return e[k]; }
13
+ var n = Object.create(null);
14
+ if (e) {
15
+ Object.keys(e).forEach(function (k) {
16
+ if (k !== 'default') {
17
+ var d = Object.getOwnPropertyDescriptor(e, k);
18
+ Object.defineProperty(n, k, d.get ? d : {
19
+ enumerable: true,
20
+ get: function () { return e[k]; }
21
+ });
22
+ }
21
23
  });
22
- }
23
- });
24
- }
25
- n.default = e;
26
- return Object.freeze(n);
24
+ }
25
+ n.default = e;
26
+ return Object.freeze(n);
27
27
  }
28
28
 
29
29
  var acorn__namespace = /*#__PURE__*/_interopNamespaceDefault(acorn);
30
30
  var walk__namespace = /*#__PURE__*/_interopNamespaceDefault(walk);
31
31
 
32
+ /******************************************************************************
33
+ Copyright (c) Microsoft Corporation.
34
+
35
+ Permission to use, copy, modify, and/or distribute this software for any
36
+ purpose with or without fee is hereby granted.
37
+
38
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
39
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
40
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
41
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
42
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
43
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
44
+ PERFORMANCE OF THIS SOFTWARE.
45
+ ***************************************************************************** */
46
+ /* global Reflect, Promise, SuppressedError, Symbol */
47
+
48
+
49
+ function __awaiter(thisArg, _arguments, P, generator) {
50
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
51
+ return new (P || (P = Promise))(function (resolve, reject) {
52
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
53
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
54
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
55
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
56
+ });
57
+ }
58
+
59
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
60
+ var e = new Error(message);
61
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
62
+ };
63
+
64
+ function apiLoader (str) {
65
+ return `import {
66
+ useAddToFavorites,
67
+ useDidHide,
68
+ useDidShow,
69
+ useError,
70
+ useLaunch,
71
+ useLoad,
72
+ useOptionMenuClick,
73
+ usePageNotFound,
74
+ usePageScroll,
75
+ usePullDownRefresh,
76
+ usePullIntercept,
77
+ useReachBottom,
78
+ useReady,
79
+ useResize,
80
+ useRouter,
81
+ useSaveExitState,
82
+ useShareAppMessage,
83
+ useShareTimeline,
84
+ useTabItemTap,
85
+ useTitleClick,
86
+ useScope,
87
+ useUnhandledRejection,
88
+ useUnload
89
+ } from '@tarojs/plugin-framework-react/dist/runtime'
90
+ ${str}
91
+
92
+ taro.useAddToFavorites = useAddToFavorites
93
+ taro.useDidHide = useDidHide
94
+ taro.useDidShow = useDidShow
95
+ taro.useError = useError
96
+ taro.useLaunch = useLaunch
97
+ taro.useLoad = useLoad
98
+ taro.useOptionMenuClick = useOptionMenuClick
99
+ taro.usePageNotFound = usePageNotFound
100
+ taro.usePageScroll = usePageScroll
101
+ taro.usePullDownRefresh = usePullDownRefresh
102
+ taro.usePullIntercept = usePullIntercept
103
+ taro.useReachBottom = useReachBottom
104
+ taro.useReady = useReady
105
+ taro.useResize = useResize
106
+ taro.useRouter = useRouter
107
+ taro.useSaveExitState = useSaveExitState
108
+ taro.useShareAppMessage = useShareAppMessage
109
+ taro.useShareTimeline = useShareTimeline
110
+ taro.useTabItemTap = useTabItemTap
111
+ taro.useTitleClick = useTitleClick
112
+ taro.useScope = useScope
113
+ taro.useUnhandledRejection = useUnhandledRejection
114
+ taro.useUnload = useUnload
115
+
116
+ export {
117
+ useAddToFavorites,
118
+ useDidHide,
119
+ useDidShow,
120
+ useError,
121
+ useLaunch,
122
+ useLoad,
123
+ useOptionMenuClick,
124
+ usePageNotFound,
125
+ usePageScroll,
126
+ usePullDownRefresh,
127
+ usePullIntercept,
128
+ useReachBottom,
129
+ useReady,
130
+ useResize,
131
+ useRouter,
132
+ useSaveExitState,
133
+ useShareAppMessage,
134
+ useShareTimeline,
135
+ useTabItemTap,
136
+ useTitleClick,
137
+ useScope,
138
+ useUnhandledRejection,
139
+ useUnload
140
+ }
141
+ `;
142
+ }
143
+
32
144
  function addConfig(source) {
33
145
  const configsMap = {
34
146
  enableShareAppMessage: ['onShareAppMessage', 'useShareAppMessage'],
@@ -86,9 +198,9 @@ import Nerv from 'nervjs';
86
198
  `,
87
199
  mockAppStatement: `
88
200
  class App extends Nerv.Component {
89
- render () {
90
- return this.props.children
91
- }
201
+ render () {
202
+ return this.props.children
203
+ }
92
204
  }
93
205
  `,
94
206
  frameworkArgs: 'Nerv, Nerv, config',
@@ -120,7 +232,7 @@ class App extends React.Component {
120
232
  if (framework === 'nerv') {
121
233
  Object.assign(loaderMeta, nervMeta);
122
234
  }
123
- if (shared.isWebPlatform()) {
235
+ if (process.env.TARO_PLATFORM === 'web') {
124
236
  if (framework === 'react') {
125
237
  const react = require('react');
126
238
  const majorVersion = Number((react.version || '18').split('.')[0]);
@@ -135,39 +247,277 @@ class App extends React.Component {
135
247
  return loaderMeta;
136
248
  }
137
249
 
250
+ function h5iVitePlugin(ctx, framework) {
251
+ return [
252
+ injectLoaderMeta$2(ctx, framework),
253
+ setTaroApi(),
254
+ esbuildExclude(framework)
255
+ ];
256
+ }
257
+ function injectLoaderMeta$2(ctx, framework) {
258
+ function customizer(object = '', sources = '') {
259
+ if ([object, sources].every(e => typeof e === 'string'))
260
+ return object + sources;
261
+ }
262
+ const { runnerUtils } = ctx;
263
+ const { getViteH5CompilerContext } = runnerUtils;
264
+ return {
265
+ name: 'taro-react:loader-meta',
266
+ buildStart() {
267
+ return __awaiter(this, void 0, void 0, function* () {
268
+ const viteCompilerContext = yield getViteH5CompilerContext(this);
269
+ if (viteCompilerContext) {
270
+ viteCompilerContext.loaderMeta = lodash.mergeWith(getLoaderMeta(framework), viteCompilerContext.loaderMeta, customizer);
271
+ }
272
+ });
273
+ }
274
+ };
275
+ }
276
+ function setTaroApi() {
277
+ // dev 环境通过 esbuild 来做; pro 环境通过 rollup load 钩子来做;因为生产环境不会走 esbuild
278
+ return {
279
+ name: 'taro-react:process-import-taro',
280
+ enforce: 'pre',
281
+ config: () => ({
282
+ optimizeDeps: {
283
+ esbuildOptions: {
284
+ plugins: [
285
+ {
286
+ name: 'taro:react-api',
287
+ setup(build) {
288
+ build.onLoad({ filter: helper.REG_TARO_H5_RUNTIME_API }, (args) => __awaiter(this, void 0, void 0, function* () {
289
+ const input = yield helper.fs.readFile(args.path, 'utf8');
290
+ return {
291
+ contents: apiLoader(input + '\n' + 'const taro = Taro__default\n')
292
+ };
293
+ }));
294
+ },
295
+ }
296
+ ]
297
+ }
298
+ },
299
+ }),
300
+ load(id) {
301
+ return __awaiter(this, void 0, void 0, function* () {
302
+ if (process.env.NODE_ENV === 'production' && helper.REG_TARO_H5_RUNTIME_API.test(id)) {
303
+ try {
304
+ const input = yield helper.fs.readFile(id, 'utf8');
305
+ return apiLoader(input + '\n' + 'const taro = Taro__default\n');
306
+ }
307
+ catch (_) {
308
+ return null;
309
+ }
310
+ }
311
+ });
312
+ }
313
+ };
314
+ }
315
+ // todo 后面看看能否把 preact 改为虚拟模块
316
+ function esbuildExclude(framework) {
317
+ if (framework !== 'preact')
318
+ return null;
319
+ return {
320
+ name: 'taro-react:esvuild-exclude',
321
+ enforce: 'pre',
322
+ config: () => ({
323
+ optimizeDeps: {
324
+ exclude: ['react', 'preact']
325
+ }
326
+ })
327
+ };
328
+ }
329
+
330
+ function harmonyVitePlugin(ctx, framework) {
331
+ return [
332
+ injectLoaderMeta$1(ctx, framework),
333
+ aliasPlugin$1(ctx, framework),
334
+ ];
335
+ }
336
+ function injectLoaderMeta$1(ctx, framework) {
337
+ return {
338
+ name: 'taro-react:loader-meta',
339
+ buildStart() {
340
+ const { runnerUtils } = ctx;
341
+ const { getViteHarmonyCompilerContext } = runnerUtils;
342
+ const viteCompilerContext = getViteHarmonyCompilerContext(this);
343
+ if (viteCompilerContext) {
344
+ viteCompilerContext.loaderMeta = getLoaderMeta(framework);
345
+ }
346
+ }
347
+ };
348
+ }
349
+ function aliasPlugin$1(ctx, framework) {
350
+ if (framework === 'react') {
351
+ return {
352
+ name: 'taro-react:alias',
353
+ config(config) {
354
+ var _a;
355
+ const alias = [
356
+ { find: /react-dom$/, replacement: '@tarojs/react' }
357
+ ];
358
+ const isProd = config.mode === 'production';
359
+ // TODO:harmony 目前会导致部分包用 production 版本,部分用 development 版本,导致许多 api 报错
360
+ const isHarmony = ctx.runOpts.options.platform === 'harmony';
361
+ if (!isProd && ((_a = ctx.initialConfig.harmony) === null || _a === void 0 ? void 0 : _a.debugReact) !== true && !isHarmony) {
362
+ // 不是生产环境,且没有设置 debugReact,则使用压缩版本的 react 依赖,减少体积
363
+ alias.push({ find: /react-reconciler$/, replacement: 'react-reconciler/cjs/react-reconciler.production.min.js' });
364
+ alias.push({ find: /react$/, replacement: 'react/cjs/react.production.min.js' });
365
+ alias.push({ find: /scheduler$/, replacement: 'scheduler/cjs/scheduler.production.min.js' });
366
+ alias.push({ find: /react\/jsx-runtime$/, replacement: 'react/cjs/react-jsx-runtime.production.min.js' });
367
+ // 在React18中,使用了exports字段约定了模块暴露路径,其中并未暴露 ./cjs/ 。这将使上面的alias在编译时报错。相当的tricky。
368
+ // Why writeJson? prebundle will load package.json via readFile to check exports property.
369
+ const reactPkgPath = require.resolve('react/package.json', { paths: [process.cwd()] });
370
+ if (reactPkgPath) {
371
+ const reactPkg = require('react/package.json');
372
+ const reactVersion = (reactPkg.version || '');
373
+ if ((/^[~^]?18/).test(reactVersion) && reactPkg.exports) {
374
+ reactPkg.exports = Object.assign(reactPkg.exports, {
375
+ './cjs/': './cjs/'
376
+ });
377
+ helper.fs.writeJsonSync(reactPkgPath, reactPkg, { spaces: 2 });
378
+ }
379
+ }
380
+ }
381
+ return {
382
+ resolve: {
383
+ alias
384
+ }
385
+ };
386
+ }
387
+ };
388
+ }
389
+ return [];
390
+ }
391
+
392
+ function miniVitePlugin(ctx, framework) {
393
+ return [
394
+ injectLoaderMeta(ctx, framework),
395
+ aliasPlugin(ctx, framework),
396
+ ];
397
+ }
398
+ function injectLoaderMeta(ctx, framework) {
399
+ return {
400
+ name: 'taro-react:loader-meta',
401
+ buildStart() {
402
+ const { runnerUtils } = ctx;
403
+ const { getViteMiniCompilerContext } = runnerUtils;
404
+ const viteCompilerContext = getViteMiniCompilerContext(this);
405
+ if (viteCompilerContext) {
406
+ viteCompilerContext.loaderMeta = getLoaderMeta(framework);
407
+ }
408
+ }
409
+ };
410
+ }
411
+ function aliasPlugin(ctx, framework) {
412
+ if (framework === 'react') {
413
+ return {
414
+ name: 'taro-react:alias',
415
+ config(config) {
416
+ var _a;
417
+ const alias = [
418
+ { find: /react-dom$/, replacement: '@tarojs/react' }
419
+ ];
420
+ const isProd = config.mode === 'production';
421
+ // TODO:harmony 目前会导致部分包用 production 版本,部分用 development 版本,导致许多 api 报错
422
+ const isHarmony = ctx.runOpts.options.platform === 'harmony';
423
+ if (!isProd && ((_a = ctx.initialConfig.mini) === null || _a === void 0 ? void 0 : _a.debugReact) !== true && !isHarmony) {
424
+ // 不是生产环境,且没有设置 debugReact,则使用压缩版本的 react 依赖,减少体积
425
+ alias.push({ find: /react-reconciler$/, replacement: 'react-reconciler/cjs/react-reconciler.production.min.js' });
426
+ alias.push({ find: /^(?!.*mobx-react$).*react$/, replacement: 'react/cjs/react.production.min.js' });
427
+ alias.push({ find: /scheduler$/, replacement: 'scheduler/cjs/scheduler.production.min.js' });
428
+ alias.push({ find: /react\/jsx-runtime$/, replacement: 'react/cjs/react-jsx-runtime.production.min.js' });
429
+ // 在React18中,使用了exports字段约定了模块暴露路径,其中并未暴露 ./cjs/ 。这将使上面的alias在编译时报错。相当的tricky。
430
+ // Why writeJson? prebundle will load package.json via readFile to check exports property.
431
+ const reactPkgPath = require.resolve('react/package.json', { paths: [process.cwd()] });
432
+ if (reactPkgPath) {
433
+ const reactPkg = require('react/package.json');
434
+ const reactVersion = (reactPkg.version || '');
435
+ if ((/^[~^]?18/).test(reactVersion) && reactPkg.exports) {
436
+ reactPkg.exports = Object.assign(reactPkg.exports, {
437
+ './cjs/': './cjs/'
438
+ });
439
+ helper.fs.writeJsonSync(reactPkgPath, reactPkg, { spaces: 2 });
440
+ }
441
+ }
442
+ }
443
+ return {
444
+ resolve: {
445
+ alias
446
+ }
447
+ };
448
+ }
449
+ };
450
+ }
451
+ return [];
452
+ }
453
+
138
454
  function modifyH5WebpackChain(ctx, framework, chain) {
139
455
  var _a;
140
- setLoader$1(framework, chain);
456
+ setLoader$2(framework, chain);
141
457
  setPlugin(ctx, framework, chain);
142
458
  const { isBuildNativeComp = false } = ((_a = ctx.runOpts) === null || _a === void 0 ? void 0 : _a.options) || {};
143
459
  const externals = {};
144
460
  if (isBuildNativeComp) {
145
461
  // Note: 该模式不支持 prebundle 优化,不必再处理
146
- externals.react = 'React';
147
- externals['react-dom'] = 'ReactDOM';
462
+ externals.react = {
463
+ commonjs: 'react',
464
+ commonjs2: 'react',
465
+ amd: 'react',
466
+ root: 'React'
467
+ };
468
+ externals['react-dom'] = {
469
+ commonjs: 'react-dom',
470
+ commonjs2: 'react-dom',
471
+ amd: 'react-dom',
472
+ root: 'ReactDOM'
473
+ };
148
474
  if (framework === 'preact') {
149
475
  externals.preact = 'preact';
150
476
  }
477
+ chain.merge({
478
+ externalsType: 'umd'
479
+ });
151
480
  }
152
481
  chain.merge({
153
482
  externals,
154
483
  module: {
155
484
  rule: {
156
- 'process-import-taro': {
157
- test: /taro-h5[\\/]dist[\\/]api[\\/]taro/,
485
+ 'process-import-taro-h5': {
486
+ test: helper.REG_TARO_H5,
487
+ loader: require.resolve('./api-loader'),
488
+ },
489
+ },
490
+ },
491
+ });
492
+ chain.merge({
493
+ externals,
494
+ module: {
495
+ rule: {
496
+ 'process-import-taro-harmony-hybrid': {
497
+ test: /taro-platform-harmony-hybrid[\\/]dist[\\/]api[\\/]apis[\\/]taro/,
498
+ loader: require.resolve('./api-loader')
499
+ }
500
+ }
501
+ },
502
+ });
503
+ chain.merge({
504
+ externals,
505
+ module: {
506
+ rule: {
507
+ 'process-import-taro-harmony-hybrid': {
508
+ test: /taro-platform-harmony-hybrid[\\/]dist[\\/]api[\\/]apis[\\/]taro/,
158
509
  loader: require.resolve('./api-loader')
159
510
  }
160
511
  }
161
512
  },
162
513
  });
163
514
  }
164
- function setLoader$1(framework, chain) {
515
+ function setLoader$2(framework, chain) {
165
516
  function customizer(object = '', sources = '') {
166
- if ([object, sources].every(e => typeof e === 'string'))
517
+ if ([object, sources].every((e) => typeof e === 'string'))
167
518
  return object + sources;
168
519
  }
169
- chain.plugin('mainPlugin')
170
- .tap(args => {
520
+ chain.plugin('mainPlugin').tap((args) => {
171
521
  args[0].loaderMeta = lodash.mergeWith(getLoaderMeta(framework), args[0].loaderMeta, customizer);
172
522
  return args;
173
523
  });
@@ -180,20 +530,58 @@ function setPlugin(ctx, framework, chain) {
180
530
  if (!isProd && ((_b = (_a = config.h5) === null || _a === void 0 ? void 0 : _a.devServer) === null || _b === void 0 ? void 0 : _b.hot) !== false) {
181
531
  // 默认开启 fast-refresh
182
532
  if (framework === 'react') {
183
- chain
184
- .plugin('fastRefreshPlugin')
185
- .use(require('@pmmmwh/react-refresh-webpack-plugin'));
533
+ chain.plugin('fastRefreshPlugin').use(require('@pmmmwh/react-refresh-webpack-plugin'));
186
534
  }
187
535
  else if (framework === 'preact') {
188
- chain
189
- .plugin('hotModuleReplacementPlugin')
190
- .use(require('webpack').HotModuleReplacementPlugin);
191
- chain
192
- .plugin('fastRefreshPlugin')
193
- .use(require('@prefresh/webpack'));
536
+ chain.plugin('hotModuleReplacementPlugin').use(require('webpack').HotModuleReplacementPlugin);
537
+ chain.plugin('fastRefreshPlugin').use(require('@prefresh/webpack'));
538
+ }
539
+ }
540
+ }
541
+
542
+ function modifyHarmonyWebpackChain(ctx, framework, chain) {
543
+ setAlias$2(ctx, framework, chain);
544
+ setLoader$1(framework, chain);
545
+ }
546
+ function setAlias$2(ctx, framework, chain) {
547
+ var _a;
548
+ const config = ctx.initialConfig;
549
+ const alias = chain.resolve.alias;
550
+ if (framework === 'react') {
551
+ alias.set('react-dom$', '@tarojs/react');
552
+ alias.set('react-dom/client$', '@tarojs/react');
553
+ const webpackConfig = chain.toConfig();
554
+ const isProd = webpackConfig.mode === 'production';
555
+ if (!isProd && ((_a = config.harmony) === null || _a === void 0 ? void 0 : _a.debugReact) !== true) {
556
+ // 不是生产环境,且没有设置 debugReact,则使用压缩版本的 react 依赖,减少体积
557
+ // 兼容pnpm workspace
558
+ const reactModulePath = require.resolve('react', { paths: [process.cwd()] });
559
+ const newFilePath = path.join(path.dirname(reactModulePath), 'cjs', 'react.production.min.js');
560
+ alias.set('react-reconciler$', 'react-reconciler/cjs/react-reconciler.production.min.js');
561
+ alias.set('react$', newFilePath);
562
+ alias.set('react/jsx-runtime$', 'react/cjs/react-jsx-runtime.production.min.js');
563
+ // 在React18中,使用了exports字段约定了模块暴露路径,其中并未暴露 ./cjs/ 。这将使上面的alias在编译时报错。相当的tricky。
564
+ // Why writeJson? prebundle will load package.json via readFile to check exports property.
565
+ const reactPkgPath = require.resolve('react/package.json', { paths: [process.cwd()] });
566
+ if (reactPkgPath) {
567
+ const reactPkg = require('react/package.json');
568
+ const reactVersion = reactPkg.version || '';
569
+ if (/^[~^]?18/.test(reactVersion) && reactPkg.exports) {
570
+ reactPkg.exports = Object.assign(reactPkg.exports, {
571
+ './cjs/': './cjs/',
572
+ });
573
+ helper.fs.writeJsonSync(reactPkgPath, reactPkg, { spaces: 2 });
574
+ }
575
+ }
194
576
  }
195
577
  }
196
578
  }
579
+ function setLoader$1(framework, chain) {
580
+ chain.plugin('mainPlugin').tap((args) => {
581
+ args[0].loaderMeta = getLoaderMeta(framework);
582
+ return args;
583
+ });
584
+ }
197
585
 
198
586
  function modifyMiniWebpackChain(ctx, framework, chain) {
199
587
  setAlias$1(ctx, framework, chain);
@@ -205,6 +593,7 @@ function setAlias$1(ctx, framework, chain) {
205
593
  const alias = chain.resolve.alias;
206
594
  if (framework === 'react') {
207
595
  alias.set('react-dom$', '@tarojs/react');
596
+ alias.set('react-dom/client$', '@tarojs/react');
208
597
  const webpackConfig = chain.toConfig();
209
598
  const isProd = webpackConfig.mode === 'production';
210
599
  if (!isProd && ((_a = config.mini) === null || _a === void 0 ? void 0 : _a.debugReact) !== true) {
@@ -213,7 +602,7 @@ function setAlias$1(ctx, framework, chain) {
213
602
  const reactModulePath = require.resolve('react', { paths: [process.cwd()] });
214
603
  const newFilePath = path.join(path.dirname(reactModulePath), 'cjs', 'react.production.min.js');
215
604
  alias.set('react-reconciler$', 'react-reconciler/cjs/react-reconciler.production.min.js');
216
- alias.set('react$', newFilePath);
605
+ alias.set(/^(?!.*mobx-react$).*react$/, newFilePath);
217
606
  alias.set('react/jsx-runtime$', 'react/cjs/react-jsx-runtime.production.min.js');
218
607
  // 在React18中,使用了exports字段约定了模块暴露路径,其中并未暴露 ./cjs/ 。这将使上面的alias在编译时报错。相当的tricky。
219
608
  // Why writeJson? prebundle will load package.json via readFile to check exports property.
@@ -238,24 +627,29 @@ function setLoader(framework, chain) {
238
627
  });
239
628
  }
240
629
 
630
+ function isReactLike(framework = 'react') {
631
+ return ['react', 'preact', 'nerv', 'solid'].includes(framework);
632
+ }
241
633
  var index = (ctx) => {
242
- const { framework } = ctx.initialConfig;
243
- if (framework !== 'react' && framework !== 'nerv' && framework !== 'preact')
634
+ const { framework = 'react' } = ctx.initialConfig;
635
+ if (!isReactLike(framework))
244
636
  return;
245
637
  ctx.modifyWebpackChain(({ chain }) => {
246
638
  // 通用
247
639
  setAlias(framework, chain);
248
- chain
249
- .plugin('definePlugin')
250
- .tap(args => {
640
+ chain.plugin('definePlugin').tap((args) => {
251
641
  const config = args[0];
252
642
  config.__TARO_FRAMEWORK__ = `"${framework}"`;
253
643
  return args;
254
644
  });
255
- if (shared.isWebPlatform()) {
645
+ if (process.env.TARO_PLATFORM === 'web') {
256
646
  // H5
257
647
  modifyH5WebpackChain(ctx, framework, chain);
258
648
  }
649
+ else if (process.env.TARO_PLATFORM === 'harmony' || process.env.TARO_ENV === 'harmony') {
650
+ // 鸿蒙
651
+ modifyHarmonyWebpackChain(ctx, framework, chain);
652
+ }
259
653
  else {
260
654
  // 小程序
261
655
  modifyMiniWebpackChain(ctx, framework, chain);
@@ -266,18 +660,13 @@ var index = (ctx) => {
266
660
  return;
267
661
  if (shared.isString(opts.compiler)) {
268
662
  opts.compiler = {
269
- type: opts.compiler
663
+ type: opts.compiler,
270
664
  };
271
665
  }
272
666
  const { compiler } = opts;
273
667
  if (compiler.type === 'webpack5') {
274
668
  // 提供给 webpack5 依赖预编译收集器的第三方依赖
275
- const deps = [
276
- 'react',
277
- 'react-dom',
278
- 'react/jsx-runtime',
279
- '@tarojs/plugin-framework-react/dist/runtime'
280
- ];
669
+ const deps = ['react', 'react-dom', 'react/jsx-runtime', '@tarojs/plugin-framework-react/dist/runtime'];
281
670
  compiler.prebundle || (compiler.prebundle = {});
282
671
  const prebundleOptions = compiler.prebundle;
283
672
  prebundleOptions.include || (prebundleOptions.include = []);
@@ -289,19 +678,42 @@ var index = (ctx) => {
289
678
  const taroReactPlugin = {
290
679
  name: 'taroReactPlugin',
291
680
  setup(build) {
292
- build.onLoad({ filter: /taro-h5[\\/]dist[\\/]api[\\/]taro/ }, ({ path }) => {
681
+ build.onLoad({ filter: helper.REG_TARO_H5 }, ({ path }) => {
682
+ const content = helper.fs.readFileSync(path).toString();
683
+ return {
684
+ contents: require('./api-loader')(content),
685
+ };
686
+ });
687
+ build.onLoad({ filter: /taro-platform-harmony-hybrid[\\/]dist[\\/]api[\\/]apis[\\/]taro/ }, ({ path }) => {
293
688
  const content = helper.fs.readFileSync(path).toString();
294
689
  return {
295
690
  contents: require('./api-loader')(content)
296
691
  };
297
692
  });
298
- }
693
+ },
299
694
  };
300
695
  prebundleOptions.esbuild || (prebundleOptions.esbuild = {});
301
696
  const esbuildConfig = prebundleOptions.esbuild;
302
697
  esbuildConfig.plugins || (esbuildConfig.plugins = []);
303
698
  esbuildConfig.plugins.push(taroReactPlugin);
304
699
  }
700
+ else if (compiler.type === 'vite') {
701
+ compiler.vitePlugins || (compiler.vitePlugins = []);
702
+ compiler.vitePlugins.push(viteCommonPlugin(framework));
703
+ compiler.vitePlugins.push(VitePresetPlugin(framework));
704
+ if (process.env.TARO_PLATFORM === 'web') {
705
+ // H5
706
+ compiler.vitePlugins.push(h5iVitePlugin(ctx, framework));
707
+ }
708
+ else if (process.env.TARO_PLATFORM === 'harmony' || process.env.TARO_ENV === 'harmony') {
709
+ // 鸿蒙
710
+ compiler.vitePlugins.push(harmonyVitePlugin(ctx, framework));
711
+ }
712
+ else {
713
+ // 小程序
714
+ compiler.vitePlugins.push(miniVitePlugin(ctx, framework));
715
+ }
716
+ }
305
717
  });
306
718
  };
307
719
  function setAlias(framework, chain) {
@@ -319,6 +731,56 @@ function setAlias(framework, chain) {
319
731
  break;
320
732
  }
321
733
  }
734
+ function VitePresetPlugin(framework) {
735
+ return framework === 'preact'
736
+ ? require('@preact/preset-vite').preact({
737
+ babel: {
738
+ plugins: [
739
+ ['@babel/plugin-proposal-decorators', { legacy: true }],
740
+ ['@babel/plugin-proposal-class-properties', { loose: true }],
741
+ ],
742
+ },
743
+ })
744
+ : require('@vitejs/plugin-react').default({
745
+ babel: {
746
+ plugins: [
747
+ ['@babel/plugin-proposal-decorators', { legacy: true }],
748
+ ['@babel/plugin-proposal-class-properties', { loose: true }],
749
+ ],
750
+ },
751
+ });
752
+ }
753
+ function viteCommonPlugin(framework) {
754
+ return {
755
+ name: 'taro-react:common',
756
+ config() {
757
+ const alias = framework === 'preact'
758
+ ? [
759
+ { find: 'react', replacement: 'preact/compat' },
760
+ { find: 'react-dom/test-utils', replacement: 'preact/test-utils' },
761
+ { find: 'react-dom', replacement: 'preact/compat' },
762
+ { find: 'react/jsx-runtime', replacement: 'preact/jsx-runtime' },
763
+ ]
764
+ : [];
765
+ return {
766
+ optimizeDeps: {
767
+ esbuildOptions: {
768
+ define: {
769
+ __TARO_FRAMEWORK__: `"${framework}"`
770
+ }
771
+ }
772
+ },
773
+ define: {
774
+ __TARO_FRAMEWORK__: `"${framework}"`,
775
+ },
776
+ resolve: {
777
+ alias,
778
+ },
779
+ };
780
+ },
781
+ };
782
+ }
322
783
 
323
784
  exports.default = index;
785
+ exports.isReactLike = isReactLike;
324
786
  //# sourceMappingURL=index.js.map