weapp-vite 1.4.1 → 1.4.3

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.
@@ -3,7 +3,7 @@ import logger from "@weapp-core/logger";
3
3
  var logger_default = logger;
4
4
 
5
5
  // package.json
6
- var version = "1.4.1";
6
+ var version = "1.4.3";
7
7
 
8
8
  // src/constants.ts
9
9
  var VERSION = version;
@@ -13,10 +13,10 @@ var supportedCssLangs = ["wxss", "scss", "less", "sass", "styl"];
13
13
  // src/context.ts
14
14
  import { createRequire } from "node:module";
15
15
  import process from "node:process";
16
- import { addExtension as addExtension2, defu, isObject, removeExtension as removeExtension2 } from "@weapp-core/shared";
16
+ import { addExtension as addExtension2, defu, isObject as isObject2, objectHash, removeExtension as removeExtension2 } from "@weapp-core/shared";
17
17
  import { watch } from "chokidar";
18
18
  import fs6 from "fs-extra";
19
- import path4 from "pathe";
19
+ import path5 from "pathe";
20
20
  import { build as tsupBuild } from "tsup";
21
21
  import { build, loadConfigFromFile } from "vite";
22
22
  import tsconfigPaths from "vite-tsconfig-paths";
@@ -37,7 +37,7 @@ function getWeappWatchOptions() {
37
37
  import { fdir as Fdir } from "fdir";
38
38
  import fs5 from "fs-extra";
39
39
  import MagicString from "magic-string";
40
- import path3 from "pathe";
40
+ import path4 from "pathe";
41
41
  import { isCSSRequest } from "vite";
42
42
 
43
43
  // src/debugger.ts
@@ -82,8 +82,10 @@ async function findJsEntry(filepath) {
82
82
  }
83
83
 
84
84
  // src/utils/json.ts
85
+ import { get, isObject, set } from "@weapp-core/shared";
85
86
  import { parse as parseJson, stringify } from "comment-json";
86
87
  import fs2 from "fs-extra";
88
+ import path2 from "pathe";
87
89
  function parseCommentJson(json) {
88
90
  return parseJson(json, void 0, true);
89
91
  }
@@ -97,16 +99,84 @@ async function readCommentJson(filepath) {
97
99
  function stringifyJson(value, replacer) {
98
100
  return stringify(value, replacer, 2);
99
101
  }
100
- function resolveJson(value) {
101
- return stringifyJson(value);
102
+ function matches(pattern, importee) {
103
+ if (pattern instanceof RegExp) {
104
+ return pattern.test(importee);
105
+ }
106
+ if (importee.length < pattern.length) {
107
+ return false;
108
+ }
109
+ if (importee === pattern) {
110
+ return true;
111
+ }
112
+ return importee.startsWith(pattern + "/");
113
+ }
114
+ function getAliasEntries({ entries } = {}) {
115
+ if (!entries) {
116
+ return [];
117
+ }
118
+ if (Array.isArray(entries)) {
119
+ return entries.map((entry) => {
120
+ return {
121
+ find: entry.find,
122
+ replacement: entry.replacement
123
+ };
124
+ });
125
+ }
126
+ return Object.entries(entries).map(([key, value]) => {
127
+ return { find: key, replacement: value };
128
+ });
129
+ }
130
+ function resolveImportee(importee, entry, aliasEntries) {
131
+ if (Array.isArray(aliasEntries)) {
132
+ if (!entry.jsonPath) {
133
+ return importee;
134
+ }
135
+ const matchedEntry = aliasEntries.find((x) => matches(x.find, importee));
136
+ if (!matchedEntry) {
137
+ return importee;
138
+ }
139
+ const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement);
140
+ return path2.relative(path2.dirname(entry.jsonPath), updatedId);
141
+ }
142
+ return importee;
143
+ }
144
+ function resolveJson(entry, aliasEntries) {
145
+ if (entry.json) {
146
+ const json = structuredClone(entry.json);
147
+ if (entry.jsonPath && Array.isArray(aliasEntries)) {
148
+ const usingComponents = get(json, "usingComponents");
149
+ if (isObject(usingComponents)) {
150
+ for (const [key, importee] of Object.entries(usingComponents)) {
151
+ const resolvedId = resolveImportee(importee, entry, aliasEntries);
152
+ set(json, `usingComponents.${key}`, resolvedId);
153
+ }
154
+ set(json, "usingComponents", usingComponents);
155
+ }
156
+ if (entry.type === "app") {
157
+ const fields = ["subPackages", "subpackages"];
158
+ for (const field of fields) {
159
+ const subPackages = get(json, field);
160
+ if (Array.isArray(subPackages)) {
161
+ for (const subPackage of subPackages) {
162
+ if (subPackage.entry) {
163
+ subPackage.entry = changeFileExtension(subPackage.entry, "js");
164
+ }
165
+ }
166
+ }
167
+ }
168
+ }
169
+ }
170
+ return stringifyJson(json);
171
+ }
102
172
  }
103
173
 
104
174
  // src/utils/projectConfig.ts
105
175
  import fs3 from "fs-extra";
106
- import path2 from "pathe";
176
+ import path3 from "pathe";
107
177
  function getProjectConfig(root, options) {
108
- const baseJsonPath = path2.resolve(root, "project.config.json");
109
- const privateJsonPath = path2.resolve(root, "project.private.config.json");
178
+ const baseJsonPath = path3.resolve(root, "project.config.json");
179
+ const privateJsonPath = path3.resolve(root, "project.private.config.json");
110
180
  let baseJson = {};
111
181
  let privateJson = {};
112
182
  if (fs3.existsSync(baseJsonPath)) {
@@ -158,10 +228,10 @@ var debug = createDebugger("weapp-vite:plugin");
158
228
  function vitePluginWeapp(ctx, subPackageMeta) {
159
229
  let configResolved;
160
230
  function relative(p) {
161
- return path3.relative(configResolved.root, p);
231
+ return path4.relative(configResolved.root, p);
162
232
  }
163
233
  function transformAbsoluteToRelative(p) {
164
- if (path3.isAbsolute(p)) {
234
+ if (path4.isAbsolute(p)) {
165
235
  return relative(p);
166
236
  }
167
237
  return p;
@@ -206,13 +276,13 @@ function vitePluginWeapp(ctx, subPackageMeta) {
206
276
  ];
207
277
  if (!subPackageMeta) {
208
278
  for (const root of Object.keys(ctx.subPackageMeta)) {
209
- ignore.push(path3.join(root, "**"));
279
+ ignore.push(path4.join(root, "**"));
210
280
  }
211
281
  }
212
282
  const baseDir = ctx.srcRoot ?? "";
213
- const targetDir = subPackageMeta ? path3.join(baseDir, subPackageMeta.subPackage.root) : baseDir;
283
+ const targetDir = subPackageMeta ? path4.join(baseDir, subPackageMeta.subPackage.root) : baseDir;
214
284
  const patterns = [
215
- path3.join(
285
+ path4.join(
216
286
  targetDir,
217
287
  "**/*.{wxml,wxs,png,jpg,jpeg,gif,svg,webp}"
218
288
  )
@@ -225,7 +295,7 @@ function vitePluginWeapp(ctx, subPackageMeta) {
225
295
  }
226
296
  ).crawl(ctx.cwd).withPromise();
227
297
  for (const file of relFiles) {
228
- const filepath = path3.resolve(ctx.cwd, file);
298
+ const filepath = path4.resolve(ctx.cwd, file);
229
299
  this.addWatchFile(filepath);
230
300
  const isMedia = !/\.(?:wxml|wxs)$/.test(file);
231
301
  this.emitFile({
@@ -238,11 +308,11 @@ function vitePluginWeapp(ctx, subPackageMeta) {
238
308
  if (entry.jsonPath) {
239
309
  this.addWatchFile(entry.jsonPath);
240
310
  if (entry.json) {
241
- const fileName = ctx.relativeSrcRoot(path3.relative(ctx.cwd, entry.jsonPath));
311
+ const fileName = ctx.relativeSrcRoot(path4.relative(ctx.cwd, entry.jsonPath));
242
312
  this.emitFile({
243
313
  type: "asset",
244
314
  fileName,
245
- source: resolveJson(entry.json)
315
+ source: resolveJson(entry, ctx.aliasEntries)
246
316
  });
247
317
  }
248
318
  }
@@ -334,9 +404,9 @@ var require2 = createRequire(import.meta.url);
334
404
  var logBuildAppFinishOnlyShowOnce = false;
335
405
  function logBuildAppFinish() {
336
406
  if (!logBuildAppFinishOnlyShowOnce) {
337
- logger_default.success("\u5E94\u7528\u6784\u5EFA\u5B8C\u6210\uFF01\u9884\u89C8\u65B9\u5F0F\uFF1A");
407
+ logger_default.success("\u5E94\u7528\u6784\u5EFA\u5B8C\u6210\uFF01\u9884\u89C8\u65B9\u5F0F ( `2` \u79CD\u9009\u5176\u4E00\u5373\u53EF)\uFF1A");
338
408
  logger_default.info("\u6267\u884C `npm run open` / `yarn open` / `pnpm open` \u76F4\u63A5\u5728 `\u5FAE\u4FE1\u5F00\u53D1\u8005\u5DE5\u5177` \u91CC\u6253\u5F00\u5F53\u524D\u5E94\u7528");
339
- logger_default.info("\u624B\u52A8\u6253\u5F00\u5FAE\u4FE1\u5F00\u53D1\u8005\u5DE5\u5177,\u5BFC\u5165\u6839\u76EE\u5F55(`project.config.json` \u6587\u4EF6\u6240\u5728\u7684\u76EE\u5F55),\u5373\u53EF\u9884\u89C8\u6548\u679C");
409
+ logger_default.info("\u6216\u624B\u52A8\u6253\u5F00\u5FAE\u4FE1\u5F00\u53D1\u8005\u5DE5\u5177,\u5BFC\u5165\u6839\u76EE\u5F55(`project.config.json` \u6587\u4EF6\u6240\u5728\u7684\u76EE\u5F55),\u5373\u53EF\u9884\u89C8\u6548\u679C");
340
410
  logBuildAppFinishOnlyShowOnce = true;
341
411
  }
342
412
  }
@@ -359,6 +429,7 @@ var CompilerContext = class {
359
429
  entries;
360
430
  appEntry;
361
431
  subPackageMeta;
432
+ aliasEntries;
362
433
  constructor(options) {
363
434
  const { cwd, isDev, inlineConfig, projectConfig, mode, packageJson } = defu(options, {
364
435
  cwd: process.cwd(),
@@ -378,13 +449,14 @@ var CompilerContext = class {
378
449
  this.subPackageMeta = {};
379
450
  this.entriesSet = /* @__PURE__ */ new Set();
380
451
  this.entries = [];
452
+ this.aliasEntries = [];
381
453
  }
382
454
  get srcRoot() {
383
455
  return this.inlineConfig?.weapp?.srcRoot ?? "";
384
456
  }
385
457
  relativeSrcRoot(p) {
386
458
  if (this.srcRoot) {
387
- return path4.relative(this.srcRoot, p);
459
+ return path5.relative(this.srcRoot, p);
388
460
  }
389
461
  return p;
390
462
  }
@@ -436,7 +508,7 @@ var CompilerContext = class {
436
508
  inlineConfig.weapp?.watch,
437
509
  {
438
510
  ignored: [
439
- path4.join(this.mpDistRoot, "**")
511
+ path5.join(this.mpDistRoot, "**")
440
512
  ],
441
513
  cwd: this.cwd
442
514
  },
@@ -459,7 +531,7 @@ var CompilerContext = class {
459
531
  watch: {
460
532
  exclude: [
461
533
  ...defaultExcluded,
462
- this.mpDistRoot ? path4.join(this.mpDistRoot, "**") : "dist/**"
534
+ this.mpDistRoot ? path5.join(this.mpDistRoot, "**") : "dist/**"
463
535
  ],
464
536
  chokidar: {
465
537
  ignored: [...defaultExcluded]
@@ -502,7 +574,7 @@ var CompilerContext = class {
502
574
  async loadDefaultConfig() {
503
575
  const projectConfig = getProjectConfig(this.cwd);
504
576
  this.projectConfig = projectConfig;
505
- const packageJsonPath = path4.resolve(this.cwd, "package.json");
577
+ const packageJsonPath = path5.resolve(this.cwd, "package.json");
506
578
  const external = [];
507
579
  if (await fs6.exists(packageJsonPath)) {
508
580
  const localPackageJson = await fs6.readJson(packageJsonPath, {
@@ -550,12 +622,37 @@ var CompilerContext = class {
550
622
  ],
551
623
  logLevel: "warn"
552
624
  });
625
+ this.aliasEntries = getAliasEntries(this.inlineConfig.weapp?.jsonAlias);
626
+ }
627
+ get dependenciesCacheFilePath() {
628
+ return path5.resolve(this.cwd, "node_modules/weapp-vite/.cache/npm.json");
629
+ }
630
+ get dependenciesCacheHash() {
631
+ return objectHash(this.packageJson.dependencies ?? {});
632
+ }
633
+ writeDependenciesCache() {
634
+ return fs6.outputJSON(this.dependenciesCacheFilePath, {
635
+ "/": this.dependenciesCacheHash
636
+ });
637
+ }
638
+ async readDependenciesCache() {
639
+ if (await fs6.exists(this.dependenciesCacheFilePath)) {
640
+ return await fs6.readJson(this.dependenciesCacheFilePath, { throws: false });
641
+ }
642
+ }
643
+ async checkDependenciesCacheOutdate() {
644
+ const json = await this.readDependenciesCache();
645
+ if (isObject2(json)) {
646
+ return this.dependenciesCacheHash !== json["/"];
647
+ }
648
+ return true;
553
649
  }
554
650
  // https://cn.vitejs.dev/guide/build.html#library-mode
555
651
  // miniprogram_dist
556
652
  // miniprogram
557
653
  // https://developers.weixin.qq.com/miniprogram/dev/devtools/npm.html#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BB%84%E4%BB%B6%E7%9B%B8%E5%85%B3%E7%A4%BA%E4%BE%8B
558
654
  async buildNpm(options) {
655
+ const isDependenciesCacheOutdate = await this.checkDependenciesCacheOutdate();
559
656
  const { sourcemap } = defu(options, { sourcemap: true });
560
657
  let packNpmRelationList = [];
561
658
  if (this.projectConfig.setting?.packNpmManually && Array.isArray(this.projectConfig.setting.packNpmRelationList)) {
@@ -569,10 +666,10 @@ var CompilerContext = class {
569
666
  ];
570
667
  }
571
668
  for (const relation of packNpmRelationList) {
572
- const packageJsonPath = path4.resolve(this.cwd, relation.packageJsonPath);
669
+ const packageJsonPath = path5.resolve(this.cwd, relation.packageJsonPath);
573
670
  if (await fs6.exists(packageJsonPath)) {
574
671
  const pkgJson = await fs6.readJson(packageJsonPath);
575
- const outDir = path4.resolve(this.cwd, relation.miniprogramNpmDistDir, "miniprogram_npm");
672
+ const outDir = path5.resolve(this.cwd, relation.miniprogramNpmDistDir, "miniprogram_npm");
576
673
  if (pkgJson.dependencies) {
577
674
  const dependencies = Object.keys(pkgJson.dependencies);
578
675
  if (dependencies.length > 0) {
@@ -581,20 +678,30 @@ var CompilerContext = class {
581
678
  const targetJson = require2(id);
582
679
  if (Reflect.has(targetJson, "miniprogram") && targetJson.miniprogram) {
583
680
  const targetJsonPath = require2.resolve(id);
681
+ const dest = path5.join(outDir, dep);
682
+ if (!isDependenciesCacheOutdate && await fs6.exists(dest)) {
683
+ logger_default.success(`${dep} \u4F9D\u8D56\u672A\u53D1\u751F\u53D8\u5316\uFF0C\u8DF3\u8FC7\u5904\u7406!`);
684
+ continue;
685
+ }
584
686
  await fs6.copy(
585
- path4.resolve(
586
- path4.dirname(targetJsonPath),
687
+ path5.resolve(
688
+ path5.dirname(targetJsonPath),
587
689
  targetJson.miniprogram
588
690
  ),
589
- path4.join(outDir, dep)
691
+ dest
590
692
  );
591
693
  } else {
694
+ const destOutDir = path5.join(outDir, dep);
695
+ if (!isDependenciesCacheOutdate && await fs6.exists(destOutDir)) {
696
+ logger_default.success(`${dep} \u4F9D\u8D56\u672A\u53D1\u751F\u53D8\u5316\uFF0C\u8DF3\u8FC7\u5904\u7406!`);
697
+ continue;
698
+ }
592
699
  await tsupBuild({
593
700
  entry: {
594
701
  index: require2.resolve(dep)
595
702
  },
596
703
  format: ["cjs"],
597
- outDir: path4.join(outDir, dep),
704
+ outDir: destOutDir,
598
705
  silent: true,
599
706
  shims: true,
600
707
  outExtension: () => {
@@ -612,20 +719,23 @@ var CompilerContext = class {
612
719
  }
613
720
  }
614
721
  }
722
+ await this.writeDependenciesCache();
615
723
  }
616
- async usingComponentsHandler(usingComponents, dirname) {
724
+ async usingComponentsHandler(entry, relDir) {
725
+ const { usingComponents } = entry.json;
617
726
  if (usingComponents) {
618
- for (const componentUrl of Object.values(usingComponents)) {
727
+ for (const [, componentUrl] of Object.entries(usingComponents)) {
619
728
  if (/plugin:\/\//.test(componentUrl)) {
620
729
  continue;
621
730
  }
622
731
  const tokens = componentUrl.split("/");
623
- if (tokens[0] && isObject(this.packageJson.dependencies) && Reflect.has(this.packageJson.dependencies, tokens[0])) {
732
+ if (tokens[0] && isObject2(this.packageJson.dependencies) && Reflect.has(this.packageJson.dependencies, tokens[0])) {
624
733
  continue;
625
734
  } else if (tokens[0] === "") {
626
- await this.scanComponentEntry(componentUrl.substring(1), path4.resolve(this.cwd, this.srcRoot));
735
+ await this.scanComponentEntry(componentUrl.substring(1), path5.resolve(this.cwd, this.srcRoot));
627
736
  } else {
628
- await this.scanComponentEntry(componentUrl, dirname);
737
+ const importee = resolveImportee(componentUrl, entry, this.aliasEntries);
738
+ await this.scanComponentEntry(importee, relDir);
629
739
  }
630
740
  }
631
741
  }
@@ -637,22 +747,24 @@ var CompilerContext = class {
637
747
  }
638
748
  async scanAppEntry() {
639
749
  this.resetEntries();
640
- const appDirname = path4.resolve(this.cwd, this.srcRoot);
641
- const appConfigFile = path4.resolve(appDirname, "app.json");
642
- const appEntry = await findJsEntry(appConfigFile);
643
- if (appEntry && await fs6.exists(appConfigFile)) {
750
+ const appDirname = path5.resolve(this.cwd, this.srcRoot);
751
+ const appConfigFile = path5.resolve(appDirname, "app.json");
752
+ const appEntryPath = await findJsEntry(appConfigFile);
753
+ if (appEntryPath && await fs6.exists(appConfigFile)) {
644
754
  const config = await readCommentJson(appConfigFile);
645
- if (isObject(config)) {
646
- this.entriesSet.add(appEntry);
647
- this.appEntry = {
648
- path: appEntry,
755
+ if (isObject2(config)) {
756
+ this.entriesSet.add(appEntryPath);
757
+ const appEntry = {
758
+ path: appEntryPath,
649
759
  json: config,
650
- jsonPath: appConfigFile
760
+ jsonPath: appConfigFile,
761
+ type: "app"
651
762
  };
652
- this.entries.push(this.appEntry);
653
- const { pages, usingComponents, subpackages = [], subPackages = [] } = config;
763
+ this.entries.push(appEntry);
764
+ this.appEntry = appEntry;
765
+ const { pages, subpackages = [], subPackages = [] } = config;
654
766
  const subs = [...subpackages, ...subPackages];
655
- await this.usingComponentsHandler(usingComponents, appDirname);
767
+ await this.usingComponentsHandler(appEntry, appDirname);
656
768
  if (Array.isArray(pages)) {
657
769
  for (const page of pages) {
658
770
  await this.scanComponentEntry(page, appDirname);
@@ -668,21 +780,21 @@ var CompilerContext = class {
668
780
  const scanComponentEntry = this.scanComponentEntry.bind(meta);
669
781
  if (Array.isArray(sub.pages)) {
670
782
  for (const page of sub.pages) {
671
- await scanComponentEntry(path4.join(sub.root, page), appDirname);
783
+ await scanComponentEntry(path5.join(sub.root, page), appDirname);
672
784
  }
673
785
  }
674
786
  if (sub.entry) {
675
- await scanComponentEntry(path4.join(sub.root, sub.entry), appDirname);
787
+ await scanComponentEntry(path5.join(sub.root, sub.entry), appDirname);
676
788
  }
677
789
  this.subPackageMeta[sub.root] = meta;
678
790
  } else {
679
791
  if (Array.isArray(sub.pages)) {
680
792
  for (const page of sub.pages) {
681
- await this.scanComponentEntry(path4.join(sub.root, page), appDirname);
793
+ await this.scanComponentEntry(path5.join(sub.root, page), appDirname);
682
794
  }
683
795
  }
684
796
  if (sub.entry) {
685
- await this.scanComponentEntry(path4.join(sub.root, sub.entry), appDirname);
797
+ await this.scanComponentEntry(path5.join(sub.root, sub.entry), appDirname);
686
798
  }
687
799
  }
688
800
  }
@@ -697,29 +809,29 @@ var CompilerContext = class {
697
809
  // https://developers.weixin.qq.com/miniprogram/dev/framework/structure.html
698
810
  // 页面可以没有 JSON
699
811
  async scanComponentEntry(componentEntry, dirname) {
700
- const entry = path4.resolve(dirname, componentEntry);
812
+ const entry = path5.resolve(dirname, componentEntry);
701
813
  const jsEntry = await findJsEntry(entry);
702
- if (jsEntry) {
814
+ const partialEntry = {
815
+ path: jsEntry
816
+ };
817
+ if (jsEntry && !this.entriesSet.has(jsEntry)) {
703
818
  this.entriesSet.add(jsEntry);
819
+ this.entries.push(partialEntry);
704
820
  }
705
821
  const configFile = changeFileExtension(entry, "json");
706
822
  if (await fs6.exists(configFile)) {
707
823
  const config = await readCommentJson(configFile);
824
+ const jsonFragment = {
825
+ json: config,
826
+ jsonPath: configFile
827
+ };
708
828
  if (jsEntry) {
709
- this.entries.push({
710
- path: jsEntry,
711
- json: config,
712
- jsonPath: configFile
713
- });
829
+ partialEntry.json = jsonFragment.json;
830
+ partialEntry.jsonPath = jsonFragment.jsonPath;
714
831
  }
715
- if (isObject(config)) {
716
- const { usingComponents } = config;
717
- await this.usingComponentsHandler(usingComponents, path4.dirname(configFile));
832
+ if (isObject2(config)) {
833
+ await this.usingComponentsHandler(jsonFragment, path5.dirname(configFile));
718
834
  }
719
- } else if (jsEntry) {
720
- this.entries.push({
721
- path: jsEntry
722
- });
723
835
  }
724
836
  }
725
837
  setRollupWatcher(watcher, root = "/") {