vite-plugin-dts 3.6.4 → 3.7.1

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/README.md CHANGED
@@ -59,18 +59,6 @@ Starting with `3.0.0`, you can use this plugin with Rollup.
59
59
 
60
60
  Here are some FAQ's and solutions.
61
61
 
62
- ### Missing some declaration files after build (before `1.7.0`)
63
-
64
- By default, the `skipDiagnostics` option is set to `true` which means type diagnostics will be skipped during the build process (some projects may have diagnostic tools such as `vue-tsc`). Files with type errors which interrupt the build process will not be emitted (declaration files won't be generated).
65
-
66
- If your project doesn't use type diagnostic tools, you can set `skipDiagnostics: false` and `logDiagnostics: true` to turn on diagnostic and logging features of this plugin. Type errors during build will be logged to the terminal.
67
-
68
- ### Type error when using both `script` and `setup-script` in Vue component (before `3.0.0`)
69
-
70
- This is usually caused by using the `defineComponent` function in both `script` and `setup-script`. When `vue/compiler-sfc` compiles these files, the default export result from `script` gets merged with the parameter object of `defineComponent` from `setup-script`. This is incompatible with parameters and types returned from `defineComponent`. This results in a type error.
71
-
72
- Here is a simple [example](https://github.com/qmhc/vite-plugin-dts/blob/main/examples/vue/components/BothScripts.vue). You should remove the `defineComponent` in `script` and export a native object directly.
73
-
74
62
  ### Type errors that are unable to infer types from packages in `node_modules`
75
63
 
76
64
  This is an existing [TypeScript issue](https://github.com/microsoft/TypeScript/issues/42873) where TypeScript infers types from packages located in `node_modules` through soft links (pnpm). A workaround is to add `baseUrl` to your `tsconfig.json` and specify the `paths` for these packages:
@@ -86,6 +74,33 @@ This is an existing [TypeScript issue](https://github.com/microsoft/TypeScript/i
86
74
  }
87
75
  ```
88
76
 
77
+ ### `Internal Error` occurs when using `rollupTypes: true`
78
+
79
+ Refer to this [issue](https://github.com/microsoft/rushstack/issues/3875), it's due to a limitation of `@microsoft/api-extractor` or TypeScript resolver.
80
+
81
+ The main reason is that `baseUrl` is specified in `tsconfig.json` and non-standard paths are used directly when imported.
82
+
83
+ For example: `baseUrl: 'src'` is specified and importing from `<root>/src/components/index.ts` in `<root>/src/index.ts`, and `import 'components'` is used instead of `import './components'`.
84
+
85
+ Currently, you need to avoid the above situation, or use aliases instead (with the `paths` option).
86
+
87
+ <details>
88
+ <summary>Legacy</summary>
89
+
90
+ ### Missing some declaration files after build (before `1.7.0`)
91
+
92
+ By default, the `skipDiagnostics` option is set to `true` which means type diagnostics will be skipped during the build process (some projects may have diagnostic tools such as `vue-tsc`). Files with type errors which interrupt the build process will not be emitted (declaration files won't be generated).
93
+
94
+ If your project doesn't use type diagnostic tools, you can set `skipDiagnostics: false` and `logDiagnostics: true` to turn on diagnostic and logging features of this plugin. Type errors during build will be logged to the terminal.
95
+
96
+ ### Type error when using both `script` and `setup-script` in Vue component (before `3.0.0`)
97
+
98
+ This is usually caused by using the `defineComponent` function in both `script` and `setup-script`. When `vue/compiler-sfc` compiles these files, the default export result from `script` gets merged with the parameter object of `defineComponent` from `setup-script`. This is incompatible with parameters and types returned from `defineComponent`. This results in a type error.
99
+
100
+ Here is a simple [example](https://github.com/qmhc/vite-plugin-dts/blob/main/examples/vue/components/BothScripts.vue). You should remove the `defineComponent` in `script` and export a native object directly.
101
+
102
+ </details>
103
+
89
104
  ## Options
90
105
 
91
106
  ```ts
@@ -343,6 +358,8 @@ export interface PluginOptions {
343
358
  /**
344
359
  * Hook called after all declaration files are written
345
360
  *
361
+ * It will be received a map (path -> content) that records those emitted files
362
+ *
346
363
  * @default () => {}
347
364
  */
348
365
  afterBuild?: () => MaybePromise<void>
@@ -354,7 +371,7 @@ export interface PluginOptions {
354
371
  Thanks for all the contributions!
355
372
 
356
373
  <a href="https://github.com/qmhc/vite-plugin-dts/graphs/contributors">
357
- <img src="https://contrib.rocks/image?repo=qmhc/vite-plugin-dts" />
374
+ <img src="https://contrib.rocks/image?repo=qmhc/vite-plugin-dts" alt="contributors" />
358
375
  </a>
359
376
 
360
377
  ## Example
package/README.zh-CN.md CHANGED
@@ -59,18 +59,6 @@ export default defineConfig({
59
59
 
60
60
  此处将收录一些常见的问题并提供一些解决方案。
61
61
 
62
- ### 打包后出现类型文件缺失 (`1.7.0` 之前)
63
-
64
- 默认情况下 `skipDiagnostics` 选项的值为 `true`,这意味着打包过程中将跳过类型检查(一些项目通常有 `vue-tsc` 等的类型检查工具),这时如果出现存在类型错误的文件,并且这是错误会中断打包过程,那么这些文件对应的类型文件将不会被生成。
65
-
66
- 如果您的项目没有依赖外部的类型检查工具,这时候可以您可以设置 `skipDiagnostics: false` 和 `logDiagnostics: true` 来打开插件的诊断与输出功能,这将帮助您检查打包过程中出现的类型错误并将错误信息输出至终端。
67
-
68
- ### Vue 组件中同时使用了 `script` 和 `setup-script` 后出现类型错误(`3.0.0` 之前)
69
-
70
- 这通常是由于分别在 `script` 和 `setup-script` 中同时使用了 `defineComponent` 方法导致的。 `vue/compiler-sfc` 为这类文件编译时会将 `script` 中的默认导出结果合并到 `setup-script` 的 `defineComponent` 的参数定义中,而 `defineComponent` 的参数类型与结果类型并不兼容,这一行为将会导致类型错误。
71
-
72
- 这是一个简单的[示例](https://github.com/qmhc/vite-plugin-dts/blob/main/example/components/BothScripts.vue),您应该将位于 `script` 中的 `defineComponent` 方法移除,直接导出一个原始的对象。
73
-
74
62
  ### 打包时出现了无法从 `node_modules` 的包中推断类型的错误
75
63
 
76
64
  这是 TypeScript 通过软链接 (pnpm) 读取 `node_modules` 中过的类型时会出现的一个已知的问题,可以参考这个 [issue](https://github.com/microsoft/TypeScript/issues/42873),目前已有的一个解决方案,在你的 `tsconfig.json` 中添加 `baseUrl` 以及在 `paths` 添加这些包的路径:
@@ -86,6 +74,33 @@ export default defineConfig({
86
74
  }
87
75
  ```
88
76
 
77
+ ### 在 `rollupTypes: true` 时出现 `Internal Error`
78
+
79
+ 参考这个 [issue](https://github.com/microsoft/rushstack/issues/3875),这是由于 `@microsoft/api-extractor` 或者是 TypeScript 解析器的一些限制导致的。
80
+
81
+ 主要原因在于 `tsconfig.json` 中指定了 `baseUrl` 并且在引入时直接使用非标准路径。
82
+
83
+ 例如:指定了 `baseUrl: 'src'` 并且在 `<root>/src/index.ts` 中引入 `<root>/src/components/index.ts` 时使用了 `import 'components'` 而不是 `import './components'`。
84
+
85
+ 目前想要正常打包,需要规避上述情况,或使用别名代替(配合 `paths` 属性)。
86
+
87
+ <details>
88
+ <summary>过时的</summary>
89
+
90
+ ### 打包后出现类型文件缺失 (`1.7.0` 之前)
91
+
92
+ 默认情况下 `skipDiagnostics` 选项的值为 `true`,这意味着打包过程中将跳过类型检查(一些项目通常有 `vue-tsc` 等的类型检查工具),这时如果出现存在类型错误的文件,并且这是错误会中断打包过程,那么这些文件对应的类型文件将不会被生成。
93
+
94
+ 如果您的项目没有依赖外部的类型检查工具,这时候可以您可以设置 `skipDiagnostics: false` 和 `logDiagnostics: true` 来打开插件的诊断与输出功能,这将帮助您检查打包过程中出现的类型错误并将错误信息输出至终端。
95
+
96
+ ### Vue 组件中同时使用了 `script` 和 `setup-script` 后出现类型错误(`3.0.0` 之前)
97
+
98
+ 这通常是由于分别在 `script` 和 `setup-script` 中同时使用了 `defineComponent` 方法导致的。 `vue/compiler-sfc` 为这类文件编译时会将 `script` 中的默认导出结果合并到 `setup-script` 的 `defineComponent` 的参数定义中,而 `defineComponent` 的参数类型与结果类型并不兼容,这一行为将会导致类型错误。
99
+
100
+ 这是一个简单的[示例](https://github.com/qmhc/vite-plugin-dts/blob/main/example/components/BothScripts.vue),您应该将位于 `script` 中的 `defineComponent` 方法移除,直接导出一个原始的对象。
101
+
102
+ </details>
103
+
89
104
  ## 选项
90
105
 
91
106
  ```ts
@@ -343,9 +358,11 @@ export interface PluginOptions {
343
358
  /**
344
359
  * 在所有类型文件被写入后调用的钩子
345
360
  *
361
+ * 它会接收一个记录了那些最终被写入的文件的映射(path -> content)
362
+ *
346
363
  * @default () => {}
347
364
  */
348
- afterBuild?: () => MaybePromise<void>
365
+ afterBuild?: (emittedFiles: Map<string, string>) => MaybePromise<void>
349
366
  }
350
367
  ```
351
368
 
@@ -354,7 +371,7 @@ export interface PluginOptions {
354
371
  感谢他们的所做的一切贡献!
355
372
 
356
373
  <a href="https://github.com/qmhc/vite-plugin-dts/graphs/contributors">
357
- <img src="https://contrib.rocks/image?repo=qmhc/vite-plugin-dts" />
374
+ <img src="https://contrib.rocks/image?repo=qmhc/vite-plugin-dts" alt="contributors" />
358
375
  </a>
359
376
 
360
377
  ## 示例
package/dist/index.cjs CHANGED
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
3
5
  const node_path = require('node:path');
4
6
  const node_fs = require('node:fs');
5
7
  const promises = require('node:fs/promises');
@@ -119,6 +121,25 @@ function removeDirIfEmpty(dir) {
119
121
  }
120
122
  return onlyHasDir;
121
123
  }
124
+ function getTsConfig(tsConfigPath, readFileSync) {
125
+ const tsConfig = {
126
+ compilerOptions: {},
127
+ ...ts__default.readConfigFile(tsConfigPath, readFileSync).config ?? {}
128
+ };
129
+ if (tsConfig.extends) {
130
+ ensureArray(tsConfig.extends).forEach((configPath) => {
131
+ const config = getTsConfig(ensureAbsolute(configPath, node_path.dirname(tsConfigPath)), readFileSync);
132
+ Object.assign(tsConfig.compilerOptions, config.compilerOptions);
133
+ if (!tsConfig.include) {
134
+ tsConfig.include = config.include;
135
+ }
136
+ if (!tsConfig.exclude) {
137
+ tsConfig.exclude = config.exclude;
138
+ }
139
+ });
140
+ }
141
+ return tsConfig;
142
+ }
122
143
  const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
123
144
  function base64Encode(number) {
124
145
  if (number >= 0 && number < BASE64_ALPHABET.length) {
@@ -206,6 +227,21 @@ function setModuleResolution(options) {
206
227
  }
207
228
  options.moduleResolution = moduleResolution;
208
229
  }
230
+ function editSourceMapDir(content, fromDir, toDir) {
231
+ const relativeOutDir = node_path.relative(fromDir, toDir);
232
+ if (relativeOutDir) {
233
+ try {
234
+ const sourceMap = JSON.parse(content);
235
+ sourceMap.sources = sourceMap.sources.map((source) => {
236
+ return normalizePath(node_path.relative(relativeOutDir, source));
237
+ });
238
+ return JSON.stringify(sourceMap);
239
+ } catch (e) {
240
+ return false;
241
+ }
242
+ }
243
+ return true;
244
+ }
209
245
 
210
246
  const dtsRE$1 = /\.d\.tsx?$/;
211
247
  function rollupDeclarationFiles({
@@ -429,6 +465,9 @@ function isAliasMatch(alias, importer) {
429
465
  return true;
430
466
  return importer.indexOf(alias.find) === 0 && (alias.find.endsWith("/") || importer.substring(alias.find.length)[0] === "/");
431
467
  }
468
+ function ensureStartWithDot(path) {
469
+ return path.startsWith(".") ? path : `./${path}`;
470
+ }
432
471
  const globalImportRE = /(?:(?:import|export)\s?(?:type)?\s?(?:(?:\{[^;\n]+\})|(?:[^;\n]+))\s?from\s?['"][^;\n]+['"])|(?:import\(['"][^;\n]+?['"]\))/g;
433
472
  const staticImportRE = /(?:import|export)\s?(?:type)?\s?\{?.+\}?\s?from\s?['"](.+)['"]/;
434
473
  const dynamicImportRE = /import\(['"]([^;\n]+?)['"]\)/;
@@ -450,13 +489,17 @@ function transformAliasImport(filePath, content, aliases, exclude = []) {
450
489
  if (exclude.some((e) => isRegExp(e) ? e.test(matchResult[1]) : String(e) === matchResult[1])) {
451
490
  return str;
452
491
  }
453
- const truthPath = node_path.isAbsolute(matchedAlias.replacement) ? normalizePath(node_path.relative(node_path.dirname(filePath), matchedAlias.replacement)) : normalizePath(matchedAlias.replacement);
492
+ const dir = node_path.dirname(filePath);
493
+ const replacement = node_path.isAbsolute(matchedAlias.replacement) ? normalizePath(node_path.relative(dir, matchedAlias.replacement)) : normalizePath(matchedAlias.replacement);
494
+ const endSlash = typeof matchedAlias.find === "string" ? matchedAlias.find.endsWith("/") : matchResult[1].match(matchedAlias.find)[0].endsWith("/");
495
+ const truthPath = matchResult[1].replace(
496
+ matchedAlias.find,
497
+ replacement + (endSlash ? "/" : "")
498
+ );
499
+ const normalizedPath = normalizePath(node_path.relative(dir, node_path.resolve(dir, truthPath)));
454
500
  return str.replace(
455
501
  isDynamic ? simpleDynamicImportRE : simpleStaticImportRE,
456
- `$1'${matchResult[1].replace(
457
- matchedAlias.find,
458
- (truthPath.startsWith(".") ? truthPath : `./${truthPath}`) + (typeof matchedAlias.find === "string" && matchedAlias.find.endsWith("/") ? "/" : "")
459
- )}'${isDynamic ? ")" : ""}`
502
+ `$1'${ensureStartWithDot(normalizedPath)}'${isDynamic ? ")" : ""}`
460
503
  );
461
504
  }
462
505
  }
@@ -496,6 +539,8 @@ const fixedCompilerOptions = {
496
539
  const noop = () => {
497
540
  };
498
541
  const extPrefix = (file) => mtjsRE.test(file) ? "m" : ctjsRE.test(file) ? "c" : "";
542
+ const regexpSymbolRE = /([$.\\+?()[\]!<=|{}^,])/g;
543
+ const asteriskRE = /[*]+/g;
499
544
  function dtsPlugin(options = {}) {
500
545
  const {
501
546
  tsconfigPath,
@@ -555,7 +600,7 @@ function dtsPlugin(options = {}) {
555
600
  return { find: key, replacement: value };
556
601
  });
557
602
  } else {
558
- aliases = ensureArray(aliasOptions);
603
+ aliases = ensureArray(aliasOptions).map((alias) => ({ ...alias }));
559
604
  }
560
605
  if (aliasesExclude.length > 0) {
561
606
  aliases = aliases.filter(
@@ -564,6 +609,9 @@ function dtsPlugin(options = {}) {
564
609
  )
565
610
  );
566
611
  }
612
+ for (const alias of aliases) {
613
+ alias.replacement = resolve(alias.replacement);
614
+ }
567
615
  },
568
616
  async configResolved(config) {
569
617
  logger = logLevel ? (await import('vite')).createLogger(logLevel, { allowClearScreen: config.clearScreen }) : config.logger;
@@ -650,16 +698,17 @@ ${logPrefix} ${kolorist.yellow(
650
698
  const { baseUrl, paths } = compilerOptions;
651
699
  if (pathsToAliases && baseUrl && paths) {
652
700
  const basePath = ensureAbsolute(baseUrl, configPath ? node_path.dirname(configPath) : root);
653
- const existsFinds = new Set(
654
- aliases.map((alias) => alias.find).filter((find) => typeof find === "string")
655
- );
656
701
  for (const [findWithAsterisk, replacements] of Object.entries(paths)) {
657
- const find = findWithAsterisk.replace("/*", "");
658
- if (!replacements.length || existsFinds.has(find))
659
- continue;
702
+ const find = new RegExp(
703
+ findWithAsterisk.replace(regexpSymbolRE, "\\$1").replace(asteriskRE, "(.+)")
704
+ );
705
+ let index = 1;
660
706
  aliases.push({
661
707
  find,
662
- replacement: ensureAbsolute(replacements[0].replace("/*", ""), basePath)
708
+ replacement: ensureAbsolute(
709
+ replacements[0].replace(asteriskRE, () => `$${index++}`),
710
+ basePath
711
+ )
663
712
  });
664
713
  }
665
714
  }
@@ -912,13 +961,14 @@ export default ${libName}
912
961
  libFolder = void 0;
913
962
  }
914
963
  const rollupFiles = /* @__PURE__ */ new Set();
964
+ const compilerOptions2 = configPath ? getTsConfig(configPath, host.readFile).compilerOptions : rawCompilerOptions;
915
965
  if (multiple) {
916
966
  for (const name of entryNames) {
917
967
  const path = cleanPath(resolve(outDir, `${name.replace(tsRE, "")}.d.ts`));
918
968
  rollupDeclarationFiles({
919
969
  root,
920
970
  configPath,
921
- compilerOptions: rawCompilerOptions,
971
+ compilerOptions: compilerOptions2,
922
972
  outDir,
923
973
  entryPath: path,
924
974
  fileName: node_path.basename(path),
@@ -933,7 +983,7 @@ export default ${libName}
933
983
  rollupDeclarationFiles({
934
984
  root,
935
985
  configPath,
936
- compilerOptions: rawCompilerOptions,
986
+ compilerOptions: compilerOptions2,
937
987
  outDir,
938
988
  entryPath: typesPath,
939
989
  fileName: node_path.basename(typesPath),
@@ -961,17 +1011,8 @@ export default ${libName}
961
1011
  extraOutDirs.map(async (targetOutDir) => {
962
1012
  const path = resolve(targetOutDir, relativePath);
963
1013
  if (wroteFile.endsWith(".map")) {
964
- const relativeOutDir = node_path.relative(outDir, targetOutDir);
965
- if (relativeOutDir) {
966
- try {
967
- const sourceMap = JSON.parse(content);
968
- sourceMap.sources = sourceMap.sources.map((source) => {
969
- return normalizePath(node_path.relative(relativeOutDir, source));
970
- });
971
- content = JSON.stringify(sourceMap);
972
- } catch (e) {
973
- logger.warn(`${logPrefix} ${kolorist.yellow("Processing source map fail:")} ${path}`);
974
- }
1014
+ if (!editSourceMapDir(content, outDir, targetOutDir)) {
1015
+ logger.warn(`${logPrefix} ${kolorist.yellow("Processing source map fail:")} ${path}`);
975
1016
  }
976
1017
  }
977
1018
  await writeOutput(path, content, targetOutDir, false);
@@ -980,7 +1021,7 @@ export default ${libName}
980
1021
  });
981
1022
  }
982
1023
  if (typeof afterBuild === "function") {
983
- await wrapPromise(afterBuild());
1024
+ await wrapPromise(afterBuild(emittedFiles));
984
1025
  }
985
1026
  bundleDebug("finish");
986
1027
  logger.info(
@@ -998,4 +1039,5 @@ export default ${libName}
998
1039
  };
999
1040
  }
1000
1041
 
1001
- module.exports = dtsPlugin;
1042
+ exports.default = dtsPlugin;
1043
+ exports.editSourceMapDir = editSourceMapDir;
package/dist/index.d.cts CHANGED
@@ -216,11 +216,15 @@ interface PluginOptions {
216
216
  /**
217
217
  * Hook called after all declaration files are written
218
218
  *
219
+ * It will be received a map (path -> content) that records those emitted files
220
+ *
219
221
  * @default () => {}
220
222
  */
221
- afterBuild?: () => MaybePromise<void>;
223
+ afterBuild?: (emittedFiles: Map<string, string>) => MaybePromise<void>;
222
224
  }
223
225
 
224
226
  declare function dtsPlugin(options?: PluginOptions): vite.Plugin;
225
227
 
226
- export { type PluginOptions, dtsPlugin as default };
228
+ declare function editSourceMapDir(content: string, fromDir: string, toDir: string): string | boolean;
229
+
230
+ export { type PluginOptions, dtsPlugin as default, editSourceMapDir };
package/dist/index.d.mts CHANGED
@@ -216,11 +216,15 @@ interface PluginOptions {
216
216
  /**
217
217
  * Hook called after all declaration files are written
218
218
  *
219
+ * It will be received a map (path -> content) that records those emitted files
220
+ *
219
221
  * @default () => {}
220
222
  */
221
- afterBuild?: () => MaybePromise<void>;
223
+ afterBuild?: (emittedFiles: Map<string, string>) => MaybePromise<void>;
222
224
  }
223
225
 
224
226
  declare function dtsPlugin(options?: PluginOptions): vite.Plugin;
225
227
 
226
- export { type PluginOptions, dtsPlugin as default };
228
+ declare function editSourceMapDir(content: string, fromDir: string, toDir: string): string | boolean;
229
+
230
+ export { type PluginOptions, dtsPlugin as default, editSourceMapDir };
package/dist/index.d.ts CHANGED
@@ -216,11 +216,15 @@ interface PluginOptions {
216
216
  /**
217
217
  * Hook called after all declaration files are written
218
218
  *
219
+ * It will be received a map (path -> content) that records those emitted files
220
+ *
219
221
  * @default () => {}
220
222
  */
221
- afterBuild?: () => MaybePromise<void>;
223
+ afterBuild?: (emittedFiles: Map<string, string>) => MaybePromise<void>;
222
224
  }
223
225
 
224
226
  declare function dtsPlugin(options?: PluginOptions): vite.Plugin;
225
227
 
226
- export { type PluginOptions, dtsPlugin as default };
228
+ declare function editSourceMapDir(content: string, fromDir: string, toDir: string): string | boolean;
229
+
230
+ export { type PluginOptions, dtsPlugin as default, editSourceMapDir };
package/dist/index.mjs CHANGED
@@ -5,7 +5,7 @@ import __cjs_mod__ from 'module';
5
5
  const __filename = __cjs_url__.fileURLToPath(import.meta.url);
6
6
  const __dirname = __cjs_path__.dirname(__filename);
7
7
  const require = __cjs_mod__.createRequire(import.meta.url);
8
- import { posix, resolve as resolve$1, isAbsolute, dirname, normalize, sep, relative, basename } from 'node:path';
8
+ import { relative, posix, resolve as resolve$1, isAbsolute, dirname, normalize, sep, basename } from 'node:path';
9
9
  import { existsSync, readdirSync, lstatSync, rmdirSync } from 'node:fs';
10
10
  import { readFile, mkdir, writeFile, unlink } from 'node:fs/promises';
11
11
  import { cpus } from 'node:os';
@@ -119,6 +119,25 @@ function removeDirIfEmpty(dir) {
119
119
  }
120
120
  return onlyHasDir;
121
121
  }
122
+ function getTsConfig(tsConfigPath, readFileSync) {
123
+ const tsConfig = {
124
+ compilerOptions: {},
125
+ ...ts.readConfigFile(tsConfigPath, readFileSync).config ?? {}
126
+ };
127
+ if (tsConfig.extends) {
128
+ ensureArray(tsConfig.extends).forEach((configPath) => {
129
+ const config = getTsConfig(ensureAbsolute(configPath, dirname(tsConfigPath)), readFileSync);
130
+ Object.assign(tsConfig.compilerOptions, config.compilerOptions);
131
+ if (!tsConfig.include) {
132
+ tsConfig.include = config.include;
133
+ }
134
+ if (!tsConfig.exclude) {
135
+ tsConfig.exclude = config.exclude;
136
+ }
137
+ });
138
+ }
139
+ return tsConfig;
140
+ }
122
141
  const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
123
142
  function base64Encode(number) {
124
143
  if (number >= 0 && number < BASE64_ALPHABET.length) {
@@ -206,6 +225,21 @@ function setModuleResolution(options) {
206
225
  }
207
226
  options.moduleResolution = moduleResolution;
208
227
  }
228
+ function editSourceMapDir(content, fromDir, toDir) {
229
+ const relativeOutDir = relative(fromDir, toDir);
230
+ if (relativeOutDir) {
231
+ try {
232
+ const sourceMap = JSON.parse(content);
233
+ sourceMap.sources = sourceMap.sources.map((source) => {
234
+ return normalizePath(relative(relativeOutDir, source));
235
+ });
236
+ return JSON.stringify(sourceMap);
237
+ } catch (e) {
238
+ return false;
239
+ }
240
+ }
241
+ return true;
242
+ }
209
243
 
210
244
  const dtsRE$1 = /\.d\.tsx?$/;
211
245
  function rollupDeclarationFiles({
@@ -429,6 +463,9 @@ function isAliasMatch(alias, importer) {
429
463
  return true;
430
464
  return importer.indexOf(alias.find) === 0 && (alias.find.endsWith("/") || importer.substring(alias.find.length)[0] === "/");
431
465
  }
466
+ function ensureStartWithDot(path) {
467
+ return path.startsWith(".") ? path : `./${path}`;
468
+ }
432
469
  const globalImportRE = /(?:(?:import|export)\s?(?:type)?\s?(?:(?:\{[^;\n]+\})|(?:[^;\n]+))\s?from\s?['"][^;\n]+['"])|(?:import\(['"][^;\n]+?['"]\))/g;
433
470
  const staticImportRE = /(?:import|export)\s?(?:type)?\s?\{?.+\}?\s?from\s?['"](.+)['"]/;
434
471
  const dynamicImportRE = /import\(['"]([^;\n]+?)['"]\)/;
@@ -450,13 +487,17 @@ function transformAliasImport(filePath, content, aliases, exclude = []) {
450
487
  if (exclude.some((e) => isRegExp(e) ? e.test(matchResult[1]) : String(e) === matchResult[1])) {
451
488
  return str;
452
489
  }
453
- const truthPath = isAbsolute(matchedAlias.replacement) ? normalizePath(relative(dirname(filePath), matchedAlias.replacement)) : normalizePath(matchedAlias.replacement);
490
+ const dir = dirname(filePath);
491
+ const replacement = isAbsolute(matchedAlias.replacement) ? normalizePath(relative(dir, matchedAlias.replacement)) : normalizePath(matchedAlias.replacement);
492
+ const endSlash = typeof matchedAlias.find === "string" ? matchedAlias.find.endsWith("/") : matchResult[1].match(matchedAlias.find)[0].endsWith("/");
493
+ const truthPath = matchResult[1].replace(
494
+ matchedAlias.find,
495
+ replacement + (endSlash ? "/" : "")
496
+ );
497
+ const normalizedPath = normalizePath(relative(dir, resolve$1(dir, truthPath)));
454
498
  return str.replace(
455
499
  isDynamic ? simpleDynamicImportRE : simpleStaticImportRE,
456
- `$1'${matchResult[1].replace(
457
- matchedAlias.find,
458
- (truthPath.startsWith(".") ? truthPath : `./${truthPath}`) + (typeof matchedAlias.find === "string" && matchedAlias.find.endsWith("/") ? "/" : "")
459
- )}'${isDynamic ? ")" : ""}`
500
+ `$1'${ensureStartWithDot(normalizedPath)}'${isDynamic ? ")" : ""}`
460
501
  );
461
502
  }
462
503
  }
@@ -496,6 +537,8 @@ const fixedCompilerOptions = {
496
537
  const noop = () => {
497
538
  };
498
539
  const extPrefix = (file) => mtjsRE.test(file) ? "m" : ctjsRE.test(file) ? "c" : "";
540
+ const regexpSymbolRE = /([$.\\+?()[\]!<=|{}^,])/g;
541
+ const asteriskRE = /[*]+/g;
499
542
  function dtsPlugin(options = {}) {
500
543
  const {
501
544
  tsconfigPath,
@@ -555,7 +598,7 @@ function dtsPlugin(options = {}) {
555
598
  return { find: key, replacement: value };
556
599
  });
557
600
  } else {
558
- aliases = ensureArray(aliasOptions);
601
+ aliases = ensureArray(aliasOptions).map((alias) => ({ ...alias }));
559
602
  }
560
603
  if (aliasesExclude.length > 0) {
561
604
  aliases = aliases.filter(
@@ -564,6 +607,9 @@ function dtsPlugin(options = {}) {
564
607
  )
565
608
  );
566
609
  }
610
+ for (const alias of aliases) {
611
+ alias.replacement = resolve(alias.replacement);
612
+ }
567
613
  },
568
614
  async configResolved(config) {
569
615
  logger = logLevel ? (await import('vite')).createLogger(logLevel, { allowClearScreen: config.clearScreen }) : config.logger;
@@ -650,16 +696,17 @@ ${logPrefix} ${yellow(
650
696
  const { baseUrl, paths } = compilerOptions;
651
697
  if (pathsToAliases && baseUrl && paths) {
652
698
  const basePath = ensureAbsolute(baseUrl, configPath ? dirname(configPath) : root);
653
- const existsFinds = new Set(
654
- aliases.map((alias) => alias.find).filter((find) => typeof find === "string")
655
- );
656
699
  for (const [findWithAsterisk, replacements] of Object.entries(paths)) {
657
- const find = findWithAsterisk.replace("/*", "");
658
- if (!replacements.length || existsFinds.has(find))
659
- continue;
700
+ const find = new RegExp(
701
+ findWithAsterisk.replace(regexpSymbolRE, "\\$1").replace(asteriskRE, "(.+)")
702
+ );
703
+ let index = 1;
660
704
  aliases.push({
661
705
  find,
662
- replacement: ensureAbsolute(replacements[0].replace("/*", ""), basePath)
706
+ replacement: ensureAbsolute(
707
+ replacements[0].replace(asteriskRE, () => `$${index++}`),
708
+ basePath
709
+ )
663
710
  });
664
711
  }
665
712
  }
@@ -912,13 +959,14 @@ export default ${libName}
912
959
  libFolder = void 0;
913
960
  }
914
961
  const rollupFiles = /* @__PURE__ */ new Set();
962
+ const compilerOptions2 = configPath ? getTsConfig(configPath, host.readFile).compilerOptions : rawCompilerOptions;
915
963
  if (multiple) {
916
964
  for (const name of entryNames) {
917
965
  const path = cleanPath(resolve(outDir, `${name.replace(tsRE, "")}.d.ts`));
918
966
  rollupDeclarationFiles({
919
967
  root,
920
968
  configPath,
921
- compilerOptions: rawCompilerOptions,
969
+ compilerOptions: compilerOptions2,
922
970
  outDir,
923
971
  entryPath: path,
924
972
  fileName: basename(path),
@@ -933,7 +981,7 @@ export default ${libName}
933
981
  rollupDeclarationFiles({
934
982
  root,
935
983
  configPath,
936
- compilerOptions: rawCompilerOptions,
984
+ compilerOptions: compilerOptions2,
937
985
  outDir,
938
986
  entryPath: typesPath,
939
987
  fileName: basename(typesPath),
@@ -961,17 +1009,8 @@ export default ${libName}
961
1009
  extraOutDirs.map(async (targetOutDir) => {
962
1010
  const path = resolve(targetOutDir, relativePath);
963
1011
  if (wroteFile.endsWith(".map")) {
964
- const relativeOutDir = relative(outDir, targetOutDir);
965
- if (relativeOutDir) {
966
- try {
967
- const sourceMap = JSON.parse(content);
968
- sourceMap.sources = sourceMap.sources.map((source) => {
969
- return normalizePath(relative(relativeOutDir, source));
970
- });
971
- content = JSON.stringify(sourceMap);
972
- } catch (e) {
973
- logger.warn(`${logPrefix} ${yellow("Processing source map fail:")} ${path}`);
974
- }
1012
+ if (!editSourceMapDir(content, outDir, targetOutDir)) {
1013
+ logger.warn(`${logPrefix} ${yellow("Processing source map fail:")} ${path}`);
975
1014
  }
976
1015
  }
977
1016
  await writeOutput(path, content, targetOutDir, false);
@@ -980,7 +1019,7 @@ export default ${libName}
980
1019
  });
981
1020
  }
982
1021
  if (typeof afterBuild === "function") {
983
- await wrapPromise(afterBuild());
1022
+ await wrapPromise(afterBuild(emittedFiles));
984
1023
  }
985
1024
  bundleDebug("finish");
986
1025
  logger.info(
@@ -998,4 +1037,4 @@ export default ${libName}
998
1037
  };
999
1038
  }
1000
1039
 
1001
- export { dtsPlugin as default };
1040
+ export { dtsPlugin as default, editSourceMapDir };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-plugin-dts",
3
- "version": "3.6.4",
3
+ "version": "3.7.1",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "author": "qmhc",
@@ -17,6 +17,7 @@
17
17
  "prettier": "pretty-quick --staged && pnpm run lint",
18
18
  "release": "tsx scripts/release.ts",
19
19
  "test": "vitest run",
20
+ "test:dev": "vitest",
20
21
  "test:react": "pnpm -C examples/react build",
21
22
  "test:svelte": "pnpm -C examples/svelte build",
22
23
  "test:ts": "pnpm -C examples/ts build",
@@ -57,43 +58,43 @@
57
58
  "volar"
58
59
  ],
59
60
  "dependencies": {
60
- "@microsoft/api-extractor": "^7.38.0",
61
- "@rollup/pluginutils": "^5.0.5",
62
- "@vue/language-core": "^1.8.20",
61
+ "@microsoft/api-extractor": "7.39.0",
62
+ "@rollup/pluginutils": "^5.1.0",
63
+ "@vue/language-core": "^1.8.26",
63
64
  "debug": "^4.3.4",
64
65
  "kolorist": "^1.8.0",
65
- "vue-tsc": "^1.8.20"
66
+ "vue-tsc": "^1.8.26"
66
67
  },
67
68
  "devDependencies": {
68
- "@commitlint/cli": "^18.0.0",
69
- "@types/debug": "^4.1.10",
70
- "@types/minimist": "^1.2.4",
71
- "@types/node": "^20.8.8",
72
- "@types/prompts": "^2.4.7",
73
- "@types/semver": "^7.5.4",
74
- "@vexip-ui/commitlint-config": "^0.2.0",
75
- "@vexip-ui/eslint-config": "^0.8.1",
69
+ "@commitlint/cli": "^18.4.3",
70
+ "@types/debug": "^4.1.12",
71
+ "@types/minimist": "^1.2.5",
72
+ "@types/node": "^20.10.5",
73
+ "@types/prompts": "^2.4.9",
74
+ "@types/semver": "^7.5.6",
75
+ "@vexip-ui/commitlint-config": "^0.3.0",
76
+ "@vexip-ui/eslint-config": "^0.11.0",
76
77
  "@vexip-ui/prettier-config": "^0.2.0",
77
78
  "@vue/eslint-config-standard": "^8.0.1",
78
79
  "@vue/eslint-config-typescript": "^12.0.0",
79
80
  "conventional-changelog-cli": "^4.1.0",
80
- "eslint": "^8.52.0",
81
+ "eslint": "^8.56.0",
81
82
  "execa": "^8.0.1",
82
83
  "husky": "^8.0.3",
83
84
  "is-ci": "^3.0.1",
84
- "lint-staged": "^15.0.2",
85
+ "lint-staged": "^15.2.0",
85
86
  "minimist": "^1.2.8",
86
87
  "pinst": "^3.0.0",
87
- "prettier": "^3.0.3",
88
+ "prettier": "^3.1.1",
88
89
  "pretty-quick": "^3.1.3",
89
90
  "prompts": "^2.4.2",
90
91
  "rimraf": "^5.0.5",
91
92
  "semver": "^7.5.4",
92
- "tsx": "^3.14.0",
93
+ "tsx": "^4.7.0",
93
94
  "typescript": "5.2.2",
94
95
  "unbuild": "^2.0.0",
95
- "vite": "^4.5.0",
96
- "vitest": "^0.34.6"
96
+ "vite": "^5.0.10",
97
+ "vitest": "^1.1.0"
97
98
  },
98
99
  "peerDependencies": {
99
100
  "typescript": "*",
@@ -106,7 +107,7 @@
106
107
  },
107
108
  "pnpm": {
108
109
  "patchedDependencies": {
109
- "@microsoft/api-extractor@7.38.0": "patches/@microsoft__api-extractor@7.38.0.patch"
110
+ "@microsoft/api-extractor@7.39.0": "patches/@microsoft__api-extractor@7.39.0.patch"
110
111
  }
111
112
  }
112
113
  }