weapp-vite 1.4.0 → 1.4.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.
@@ -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.0";
6
+ var version = "1.4.2";
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,71 @@ 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
+ }
157
+ return stringifyJson(json);
158
+ }
102
159
  }
103
160
 
104
161
  // src/utils/projectConfig.ts
105
162
  import fs3 from "fs-extra";
106
- import path2 from "pathe";
163
+ import path3 from "pathe";
107
164
  function getProjectConfig(root, options) {
108
- const baseJsonPath = path2.resolve(root, "project.config.json");
109
- const privateJsonPath = path2.resolve(root, "project.private.config.json");
165
+ const baseJsonPath = path3.resolve(root, "project.config.json");
166
+ const privateJsonPath = path3.resolve(root, "project.private.config.json");
110
167
  let baseJson = {};
111
168
  let privateJson = {};
112
169
  if (fs3.existsSync(baseJsonPath)) {
@@ -158,10 +215,10 @@ var debug = createDebugger("weapp-vite:plugin");
158
215
  function vitePluginWeapp(ctx, subPackageMeta) {
159
216
  let configResolved;
160
217
  function relative(p) {
161
- return path3.relative(configResolved.root, p);
218
+ return path4.relative(configResolved.root, p);
162
219
  }
163
220
  function transformAbsoluteToRelative(p) {
164
- if (path3.isAbsolute(p)) {
221
+ if (path4.isAbsolute(p)) {
165
222
  return relative(p);
166
223
  }
167
224
  return p;
@@ -206,13 +263,13 @@ function vitePluginWeapp(ctx, subPackageMeta) {
206
263
  ];
207
264
  if (!subPackageMeta) {
208
265
  for (const root of Object.keys(ctx.subPackageMeta)) {
209
- ignore.push(path3.join(root, "**"));
266
+ ignore.push(path4.join(root, "**"));
210
267
  }
211
268
  }
212
269
  const baseDir = ctx.srcRoot ?? "";
213
- const targetDir = subPackageMeta ? path3.join(baseDir, subPackageMeta.subPackage.root) : baseDir;
270
+ const targetDir = subPackageMeta ? path4.join(baseDir, subPackageMeta.subPackage.root) : baseDir;
214
271
  const patterns = [
215
- path3.join(
272
+ path4.join(
216
273
  targetDir,
217
274
  "**/*.{wxml,wxs,png,jpg,jpeg,gif,svg,webp}"
218
275
  )
@@ -225,7 +282,7 @@ function vitePluginWeapp(ctx, subPackageMeta) {
225
282
  }
226
283
  ).crawl(ctx.cwd).withPromise();
227
284
  for (const file of relFiles) {
228
- const filepath = path3.resolve(ctx.cwd, file);
285
+ const filepath = path4.resolve(ctx.cwd, file);
229
286
  this.addWatchFile(filepath);
230
287
  const isMedia = !/\.(?:wxml|wxs)$/.test(file);
231
288
  this.emitFile({
@@ -238,11 +295,11 @@ function vitePluginWeapp(ctx, subPackageMeta) {
238
295
  if (entry.jsonPath) {
239
296
  this.addWatchFile(entry.jsonPath);
240
297
  if (entry.json) {
241
- const fileName = ctx.relativeSrcRoot(path3.relative(ctx.cwd, entry.jsonPath));
298
+ const fileName = ctx.relativeSrcRoot(path4.relative(ctx.cwd, entry.jsonPath));
242
299
  this.emitFile({
243
300
  type: "asset",
244
301
  fileName,
245
- source: resolveJson(entry.json)
302
+ source: resolveJson(entry, ctx.aliasEntries)
246
303
  });
247
304
  }
248
305
  }
@@ -282,25 +339,39 @@ function vitePluginWeapp(ctx, subPackageMeta) {
282
339
  watchChange(id, change) {
283
340
  logger_default.success(`[${change.event}] ${transformAbsoluteToRelative(id)}`);
284
341
  },
342
+ // transform(code, id, options) {
343
+ // console.log(id)
344
+ // },
345
+ // 调试监听
346
+ buildEnd() {
347
+ const watchFiles = this.getWatchFiles();
348
+ debug?.("watchFiles count: ", watchFiles.length);
349
+ },
285
350
  generateBundle(_options, bundle) {
286
351
  const bundleKeys = Object.keys(bundle);
287
352
  for (const bundleKey of bundleKeys) {
288
353
  const asset = bundle[bundleKey];
289
- if (bundleKey.endsWith(".css") && asset.type === "asset" && typeof asset.originalFileName === "string" && isJsOrTs(asset.originalFileName)) {
290
- const newFileName = ctx.relativeSrcRoot(
291
- changeFileExtension(asset.originalFileName, "wxss")
292
- );
293
- this.emitFile({
294
- type: "asset",
295
- fileName: newFileName,
296
- source: asset.source
297
- });
354
+ if (bundleKey.endsWith(".css") && asset.type === "asset") {
355
+ for (const originalFileName of asset.originalFileNames) {
356
+ if (isJsOrTs(originalFileName)) {
357
+ const newFileName = ctx.relativeSrcRoot(
358
+ changeFileExtension(originalFileName, "wxss")
359
+ );
360
+ this.emitFile({
361
+ type: "asset",
362
+ fileName: newFileName,
363
+ source: asset.source
364
+ });
365
+ }
366
+ }
298
367
  delete bundle[bundleKey];
299
368
  }
300
369
  }
301
370
  }
302
371
  // writeBundle(options, bundle) {
303
- // console.log(options, bundle)
372
+ // // console.log(options, bundle)
373
+ // const watchFiles = this.getWatchFiles()
374
+ // console.log(watchFiles)
304
375
  // },
305
376
  },
306
377
  {
@@ -345,6 +416,7 @@ var CompilerContext = class {
345
416
  entries;
346
417
  appEntry;
347
418
  subPackageMeta;
419
+ aliasEntries;
348
420
  constructor(options) {
349
421
  const { cwd, isDev, inlineConfig, projectConfig, mode, packageJson } = defu(options, {
350
422
  cwd: process.cwd(),
@@ -364,13 +436,14 @@ var CompilerContext = class {
364
436
  this.subPackageMeta = {};
365
437
  this.entriesSet = /* @__PURE__ */ new Set();
366
438
  this.entries = [];
439
+ this.aliasEntries = [];
367
440
  }
368
441
  get srcRoot() {
369
442
  return this.inlineConfig?.weapp?.srcRoot ?? "";
370
443
  }
371
444
  relativeSrcRoot(p) {
372
445
  if (this.srcRoot) {
373
- return path4.relative(this.srcRoot, p);
446
+ return path5.relative(this.srcRoot, p);
374
447
  }
375
448
  return p;
376
449
  }
@@ -422,7 +495,7 @@ var CompilerContext = class {
422
495
  inlineConfig.weapp?.watch,
423
496
  {
424
497
  ignored: [
425
- path4.join(this.mpDistRoot, "**")
498
+ path5.join(this.mpDistRoot, "**")
426
499
  ],
427
500
  cwd: this.cwd
428
501
  },
@@ -443,7 +516,13 @@ var CompilerContext = class {
443
516
  plugins: [vitePluginWeapp(this, subPackageMeta)],
444
517
  build: {
445
518
  watch: {
446
- exclude: ["node_modules/**", this.mpDistRoot ? path4.join(this.mpDistRoot, "**") : "dist/**"]
519
+ exclude: [
520
+ ...defaultExcluded,
521
+ this.mpDistRoot ? path5.join(this.mpDistRoot, "**") : "dist/**"
522
+ ],
523
+ chokidar: {
524
+ ignored: [...defaultExcluded]
525
+ }
447
526
  },
448
527
  minify: false,
449
528
  emptyOutDir: false
@@ -482,7 +561,7 @@ var CompilerContext = class {
482
561
  async loadDefaultConfig() {
483
562
  const projectConfig = getProjectConfig(this.cwd);
484
563
  this.projectConfig = projectConfig;
485
- const packageJsonPath = path4.resolve(this.cwd, "package.json");
564
+ const packageJsonPath = path5.resolve(this.cwd, "package.json");
486
565
  const external = [];
487
566
  if (await fs6.exists(packageJsonPath)) {
488
567
  const localPackageJson = await fs6.readJson(packageJsonPath, {
@@ -510,11 +589,11 @@ var CompilerContext = class {
510
589
  if (name.endsWith(".ts")) {
511
590
  const baseFileName = removeExtension2(name);
512
591
  if (baseFileName.endsWith(".wxs")) {
513
- return path4.normalize(baseFileName);
592
+ return baseFileName;
514
593
  }
515
- return path4.normalize(addExtension2(baseFileName, ".js"));
594
+ return addExtension2(baseFileName, ".js");
516
595
  }
517
- return path4.normalize(name);
596
+ return name;
518
597
  }
519
598
  },
520
599
  external
@@ -530,12 +609,37 @@ var CompilerContext = class {
530
609
  ],
531
610
  logLevel: "warn"
532
611
  });
612
+ this.aliasEntries = getAliasEntries(this.inlineConfig.weapp?.jsonAlias);
613
+ }
614
+ get dependenciesCacheFilePath() {
615
+ return path5.resolve(this.cwd, "node_modules/weapp-vite/.cache/npm.json");
616
+ }
617
+ get dependenciesCacheHash() {
618
+ return objectHash(this.packageJson.dependencies ?? {});
619
+ }
620
+ writeDependenciesCache() {
621
+ return fs6.outputJSON(this.dependenciesCacheFilePath, {
622
+ "/": this.dependenciesCacheHash
623
+ });
624
+ }
625
+ async readDependenciesCache() {
626
+ if (await fs6.exists(this.dependenciesCacheFilePath)) {
627
+ return await fs6.readJson(this.dependenciesCacheFilePath, { throws: false });
628
+ }
629
+ }
630
+ async checkDependenciesCacheOutdate() {
631
+ const json = await this.readDependenciesCache();
632
+ if (isObject2(json)) {
633
+ return this.dependenciesCacheHash !== json["/"];
634
+ }
635
+ return true;
533
636
  }
534
637
  // https://cn.vitejs.dev/guide/build.html#library-mode
535
638
  // miniprogram_dist
536
639
  // miniprogram
537
640
  // 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
538
641
  async buildNpm(options) {
642
+ const isDependenciesCacheOutdate = await this.checkDependenciesCacheOutdate();
539
643
  const { sourcemap } = defu(options, { sourcemap: true });
540
644
  let packNpmRelationList = [];
541
645
  if (this.projectConfig.setting?.packNpmManually && Array.isArray(this.projectConfig.setting.packNpmRelationList)) {
@@ -549,10 +653,10 @@ var CompilerContext = class {
549
653
  ];
550
654
  }
551
655
  for (const relation of packNpmRelationList) {
552
- const packageJsonPath = path4.resolve(this.cwd, relation.packageJsonPath);
656
+ const packageJsonPath = path5.resolve(this.cwd, relation.packageJsonPath);
553
657
  if (await fs6.exists(packageJsonPath)) {
554
658
  const pkgJson = await fs6.readJson(packageJsonPath);
555
- const outDir = path4.resolve(this.cwd, relation.miniprogramNpmDistDir, "miniprogram_npm");
659
+ const outDir = path5.resolve(this.cwd, relation.miniprogramNpmDistDir, "miniprogram_npm");
556
660
  if (pkgJson.dependencies) {
557
661
  const dependencies = Object.keys(pkgJson.dependencies);
558
662
  if (dependencies.length > 0) {
@@ -561,20 +665,30 @@ var CompilerContext = class {
561
665
  const targetJson = require2(id);
562
666
  if (Reflect.has(targetJson, "miniprogram") && targetJson.miniprogram) {
563
667
  const targetJsonPath = require2.resolve(id);
668
+ const dest = path5.join(outDir, dep);
669
+ if (!isDependenciesCacheOutdate && await fs6.exists(dest)) {
670
+ logger_default.success(`${dep} \u4F9D\u8D56\u672A\u53D1\u751F\u53D8\u5316\uFF0C\u8DF3\u8FC7\u5904\u7406!`);
671
+ continue;
672
+ }
564
673
  await fs6.copy(
565
- path4.resolve(
566
- path4.dirname(targetJsonPath),
674
+ path5.resolve(
675
+ path5.dirname(targetJsonPath),
567
676
  targetJson.miniprogram
568
677
  ),
569
- path4.join(outDir, dep)
678
+ dest
570
679
  );
571
680
  } else {
681
+ const destOutDir = path5.join(outDir, dep);
682
+ if (!isDependenciesCacheOutdate && await fs6.exists(destOutDir)) {
683
+ logger_default.success(`${dep} \u4F9D\u8D56\u672A\u53D1\u751F\u53D8\u5316\uFF0C\u8DF3\u8FC7\u5904\u7406!`);
684
+ continue;
685
+ }
572
686
  await tsupBuild({
573
687
  entry: {
574
688
  index: require2.resolve(dep)
575
689
  },
576
690
  format: ["cjs"],
577
- outDir: path4.join(outDir, dep),
691
+ outDir: destOutDir,
578
692
  silent: true,
579
693
  shims: true,
580
694
  outExtension: () => {
@@ -592,20 +706,23 @@ var CompilerContext = class {
592
706
  }
593
707
  }
594
708
  }
709
+ await this.writeDependenciesCache();
595
710
  }
596
- async usingComponentsHandler(usingComponents, dirname) {
711
+ async usingComponentsHandler(entry, relDir) {
712
+ const { usingComponents } = entry.json;
597
713
  if (usingComponents) {
598
- for (const componentUrl of Object.values(usingComponents)) {
714
+ for (const [, componentUrl] of Object.entries(usingComponents)) {
599
715
  if (/plugin:\/\//.test(componentUrl)) {
600
716
  continue;
601
717
  }
602
718
  const tokens = componentUrl.split("/");
603
- if (tokens[0] && isObject(this.packageJson.dependencies) && Reflect.has(this.packageJson.dependencies, tokens[0])) {
719
+ if (tokens[0] && isObject2(this.packageJson.dependencies) && Reflect.has(this.packageJson.dependencies, tokens[0])) {
604
720
  continue;
605
721
  } else if (tokens[0] === "") {
606
- await this.scanComponentEntry(componentUrl.substring(1), path4.resolve(this.cwd, this.srcRoot));
722
+ await this.scanComponentEntry(componentUrl.substring(1), path5.resolve(this.cwd, this.srcRoot));
607
723
  } else {
608
- await this.scanComponentEntry(componentUrl, dirname);
724
+ const importee = resolveImportee(componentUrl, entry, this.aliasEntries);
725
+ await this.scanComponentEntry(importee, relDir);
609
726
  }
610
727
  }
611
728
  }
@@ -617,22 +734,23 @@ var CompilerContext = class {
617
734
  }
618
735
  async scanAppEntry() {
619
736
  this.resetEntries();
620
- const appDirname = path4.resolve(this.cwd, this.srcRoot);
621
- const appConfigFile = path4.resolve(appDirname, "app.json");
622
- const appEntry = await findJsEntry(appConfigFile);
623
- if (appEntry && await fs6.exists(appConfigFile)) {
737
+ const appDirname = path5.resolve(this.cwd, this.srcRoot);
738
+ const appConfigFile = path5.resolve(appDirname, "app.json");
739
+ const appEntryPath = await findJsEntry(appConfigFile);
740
+ if (appEntryPath && await fs6.exists(appConfigFile)) {
624
741
  const config = await readCommentJson(appConfigFile);
625
- if (isObject(config)) {
626
- this.entriesSet.add(appEntry);
627
- this.appEntry = {
628
- path: appEntry,
742
+ if (isObject2(config)) {
743
+ this.entriesSet.add(appEntryPath);
744
+ const appEntry = {
745
+ path: appEntryPath,
629
746
  json: config,
630
747
  jsonPath: appConfigFile
631
748
  };
632
- this.entries.push(this.appEntry);
633
- const { pages, usingComponents, subpackages = [], subPackages = [] } = config;
749
+ this.entries.push(appEntry);
750
+ this.appEntry = appEntry;
751
+ const { pages, subpackages = [], subPackages = [] } = config;
634
752
  const subs = [...subpackages, ...subPackages];
635
- await this.usingComponentsHandler(usingComponents, appDirname);
753
+ await this.usingComponentsHandler(appEntry, appDirname);
636
754
  if (Array.isArray(pages)) {
637
755
  for (const page of pages) {
638
756
  await this.scanComponentEntry(page, appDirname);
@@ -648,21 +766,21 @@ var CompilerContext = class {
648
766
  const scanComponentEntry = this.scanComponentEntry.bind(meta);
649
767
  if (Array.isArray(sub.pages)) {
650
768
  for (const page of sub.pages) {
651
- await scanComponentEntry(path4.join(sub.root, page), appDirname);
769
+ await scanComponentEntry(path5.join(sub.root, page), appDirname);
652
770
  }
653
771
  }
654
772
  if (sub.entry) {
655
- await scanComponentEntry(path4.join(sub.root, sub.entry), appDirname);
773
+ await scanComponentEntry(path5.join(sub.root, sub.entry), appDirname);
656
774
  }
657
775
  this.subPackageMeta[sub.root] = meta;
658
776
  } else {
659
777
  if (Array.isArray(sub.pages)) {
660
778
  for (const page of sub.pages) {
661
- await this.scanComponentEntry(path4.join(sub.root, page), appDirname);
779
+ await this.scanComponentEntry(path5.join(sub.root, page), appDirname);
662
780
  }
663
781
  }
664
782
  if (sub.entry) {
665
- await this.scanComponentEntry(path4.join(sub.root, sub.entry), appDirname);
783
+ await this.scanComponentEntry(path5.join(sub.root, sub.entry), appDirname);
666
784
  }
667
785
  }
668
786
  }
@@ -677,29 +795,29 @@ var CompilerContext = class {
677
795
  // https://developers.weixin.qq.com/miniprogram/dev/framework/structure.html
678
796
  // 页面可以没有 JSON
679
797
  async scanComponentEntry(componentEntry, dirname) {
680
- const entry = path4.resolve(dirname, componentEntry);
798
+ const entry = path5.resolve(dirname, componentEntry);
681
799
  const jsEntry = await findJsEntry(entry);
682
- if (jsEntry) {
800
+ const partialEntry = {
801
+ path: jsEntry
802
+ };
803
+ if (jsEntry && !this.entriesSet.has(jsEntry)) {
683
804
  this.entriesSet.add(jsEntry);
805
+ this.entries.push(partialEntry);
684
806
  }
685
807
  const configFile = changeFileExtension(entry, "json");
686
808
  if (await fs6.exists(configFile)) {
687
809
  const config = await readCommentJson(configFile);
810
+ const jsonFragment = {
811
+ json: config,
812
+ jsonPath: configFile
813
+ };
688
814
  if (jsEntry) {
689
- this.entries.push({
690
- path: jsEntry,
691
- json: config,
692
- jsonPath: configFile
693
- });
815
+ partialEntry.json = jsonFragment.json;
816
+ partialEntry.jsonPath = jsonFragment.jsonPath;
694
817
  }
695
- if (isObject(config)) {
696
- const { usingComponents } = config;
697
- await this.usingComponentsHandler(usingComponents, path4.dirname(configFile));
818
+ if (isObject2(config)) {
819
+ await this.usingComponentsHandler(jsonFragment, path5.dirname(configFile));
698
820
  }
699
- } else if (jsEntry) {
700
- this.entries.push({
701
- path: jsEntry
702
- });
703
821
  }
704
822
  }
705
823
  setRollupWatcher(watcher, root = "/") {