vite-plugin-dts 1.1.1 → 1.3.0

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.zh-CN.md CHANGED
@@ -1,191 +1,191 @@
1
- # vite-plugin-dts
2
-
3
- **中文** | [English](./README.md)
4
-
5
- 一款用于在 [库模式](https://cn.vitejs.dev/guide/build.html#library-mode) 中,从 `.ts` 或 `.vue` 源文件生成类型文件(`.d.ts`)的 Vite 插件。
6
-
7
- ## 安装
8
-
9
- ```sh
10
- pnpm add vite-plugin-dts -D
11
- ```
12
-
13
- ## 使用
14
-
15
- 在 `vite.config.ts`:
16
-
17
- ```ts
18
- import { resolve } from 'path'
19
- import { defineConfig } from 'vite'
20
- import dts from 'vite-plugin-dts'
21
-
22
- export default defineConfig({
23
- build: {
24
- lib: {
25
- entry: resolve(__dirname, 'src/index.ts'),
26
- name: 'MyLib',
27
- formats: ['es'],
28
- fileName: 'my-lib'
29
- }
30
- },
31
- plugins: [dts()]
32
- })
33
- ```
34
-
35
- 在你的组件中:
36
-
37
- ```vue
38
- <template>
39
- <div></div>
40
- </template>
41
-
42
- <script lang="ts">
43
- // 使用 defineComponent 来进行类型推断
44
- import { defineComponent } from 'vue'
45
-
46
- export default defineComponent({
47
- name: 'Component'
48
- })
49
- </script>
50
- ```
51
-
52
- ```vue
53
- <script setup lang="ts">
54
- // 尽管没有直接使用 props,你仍需要接收 defineProps 的返回值
55
- const props = defineProps<{
56
- color: 'blue' | 'red'
57
- }>()
58
- </script>
59
-
60
- <template>
61
- <div>{{ color }}</div>
62
- </template>
63
- ```
64
-
65
- ## 选项
66
-
67
- ```ts
68
- import type { ts, Diagnostic } from 'ts-morph'
69
-
70
- interface TransformWriteFile {
71
- filePath?: string
72
- content?: string
73
- }
74
-
75
- export interface PluginOptions {
76
- // 执行的根目录
77
- // 默认基于 vite 配置的 root 选项
78
- root?: string
79
-
80
- // 声明文件的输出目录
81
- // 默认基于 vite 配置的输出目录
82
- outputDir?: string
83
-
84
- // 用于手动设置入口文件的根路径
85
- // 在计算每个文件的输出路径时将基于该路径
86
- // 默认为所有文件的最小公共路径
87
- entryRoot?: string
88
-
89
- // 提供给 ts-morph Project 初始化的 compilerOptions 选项
90
- // 默认值: null
91
- compilerOptions?: ts.CompilerOptions | null
92
-
93
- // 提供给 ts-morph Project 初始化的 tsconfig.json 路径
94
- // 插件也会读取 tsconfig.json 的 incldue 和 exclude 选项来解析文件
95
- // 默认值: 'tsconfig.json'
96
- tsConfigFilePath?: string
97
-
98
- // 是否将 '.vue.d.ts' 文件名转换为 '.d.ts'
99
- // 默认值: false
100
- cleanVueFileName?: boolean
101
-
102
- //是否将动态引入转换为静态
103
- // 当开启打包类型文件时强制为 true
104
- // eg. 'import('vue').DefineComponent' 转换为 'import { DefineComponent } from "vue"'
105
- // 默认值: false
106
- staticImport?: boolean
107
-
108
- // 手动设置包含路径的 glob
109
- // 默认基于 tsconfig.json 的 include 选项
110
- include?: string | string[]
111
-
112
- // 手动设置排除路径的 glob
113
- // 默认基于 tsconfig.json 的 exclude 选线,未设置时为 'node_module/**'
114
- exclude?: string | string[]
115
-
116
- // 是否生成类型声明入口
117
- // 当为 true 时会基于 package.json 的 tpyes 字段生成,或者 `${outputDir}/index.d.ts`
118
- // 当开启打包类型文件时强制为 true
119
- // 默认值: false
120
- insertTypesEntry?: boolean
121
-
122
- // 设置是否在发出类型文件后将其打包
123
- // 基于 `@microsoft/api-extractor`,由于这开启了一个新的进程,将会消耗一些时间
124
- // 默认值: false
125
- rollupTypes?: boolean
126
-
127
- // 是否将源码里的 .d.ts 文件复制到 outputDir
128
- // 默认值: true
129
- copyDtsFiles?: boolean
130
-
131
- // 出现类型诊断信息时不生成类型文件
132
- // 默认值: false
133
- noEmitOnError?: boolean
134
-
135
- // 是否跳过类型诊断
136
- // 跳过类型诊断意味着出现错误时不会中断打包进程的执行
137
- // 但对于出现错误的源文件,将无法生成相应的类型文件
138
- // 默认值: true
139
- skipDiagnostics?: boolean
140
-
141
- // 是否打印类型诊断信息
142
- // 当跳过类型诊断时该属性将不会生效
143
- // 默认值: false
144
- logDiagnostics?: boolean
145
-
146
- // 获取诊断信息后的钩子
147
- // 可以根据参数 length 来判断有误类型错误
148
- // 默认值: () => {}
149
- afterDiagnostic?: (diagnostics: Diagnostic[]) => void | Promise<void>
150
-
151
- // 类型声明文件被写入前的钩子
152
- // 可以在钩子里转换文件路径和文件内容
153
- // 默认值: () => {}
154
- beforeWriteFile?: (filePath: string, content: string) => void | TransformWriteFile
155
-
156
- // 构建后回调钩子
157
- // 将会在所有类型文件被写入后调用
158
- // 默认值: () => {}
159
- afterBuild?: () => void | Promise<void>
160
- }
161
- ```
162
-
163
- ## 示例
164
-
165
- 克隆项目然后执行下列命令:
166
-
167
- ```sh
168
- pnpm run test:e2e
169
- ```
170
-
171
- 然后检查 `example/types` 目录。
172
-
173
- ## 常见问题
174
-
175
- 此处将收录一些常见的问题并提供一些解决方案。
176
-
177
- ### 打包后出现类型文件缺失
178
-
179
- 默认情况下 `skipDiagnostics` 选项的值为 `true`,这意味着打包过程中将跳过类型检查(一些项目通常有 `vue-tsc` 等的类型检查工具),这时如果出现存在类型错误的文件,并且这是错误会中断打包过程,那么这些文件对应的类型文件将不会被生成。
180
-
181
- 如果您的项目没有依赖外部的类型检查工具,这时候可以您可以设置 `skipDiagnostics: false` 和 `logDiagnostics: true` 来打开插件的诊断与输出功能,这将帮助您检查打包过程中出现的类型错误并将错误信息输出至终端。
182
-
183
- ### Vue 组件中同时使用了 `script` 和 `setup-script` 后出现类型错误
184
-
185
- 这通常是由于分别在 `script` 和 `setup-script` 中同时使用了 `defineComponent` 方法导致的。 `vue/compiler-sfc` 为这类文件编译时会将 `script` 中的默认导出结果合并到 `setup-script` 的 `defineComponent` 的参数定义中,而 `defineComponent` 的参数类型与结果类型并不兼容,这一行为将会导致类型错误。
186
-
187
- 这是一个简单的[示例](https://github.com/qmhc/vite-plugin-dts/blob/main/example/components/BothScripts.vue),您应该将位于 `script` 中的 `defineComponent` 方法移除,直接导出一个原始的对象。
188
-
189
- ## 授权
190
-
191
- MIT 授权。
1
+ # vite-plugin-dts
2
+
3
+ **中文** | [English](./README.md)
4
+
5
+ 一款用于在 [库模式](https://cn.vitejs.dev/guide/build.html#library-mode) 中,从 `.ts` 或 `.vue` 源文件生成类型文件(`.d.ts`)的 Vite 插件。
6
+
7
+ ## 安装
8
+
9
+ ```sh
10
+ pnpm add vite-plugin-dts -D
11
+ ```
12
+
13
+ ## 使用
14
+
15
+ 在 `vite.config.ts`:
16
+
17
+ ```ts
18
+ import { resolve } from 'path'
19
+ import { defineConfig } from 'vite'
20
+ import dts from 'vite-plugin-dts'
21
+
22
+ export default defineConfig({
23
+ build: {
24
+ lib: {
25
+ entry: resolve(__dirname, 'src/index.ts'),
26
+ name: 'MyLib',
27
+ formats: ['es'],
28
+ fileName: 'my-lib'
29
+ }
30
+ },
31
+ plugins: [dts()]
32
+ })
33
+ ```
34
+
35
+ 在你的组件中:
36
+
37
+ ```vue
38
+ <template>
39
+ <div></div>
40
+ </template>
41
+
42
+ <script lang="ts">
43
+ // 使用 defineComponent 来进行类型推断
44
+ import { defineComponent } from 'vue'
45
+
46
+ export default defineComponent({
47
+ name: 'Component'
48
+ })
49
+ </script>
50
+ ```
51
+
52
+ ```vue
53
+ <script setup lang="ts">
54
+ // 尽管没有直接使用 props,你仍需要接收 defineProps 的返回值
55
+ const props = defineProps<{
56
+ color: 'blue' | 'red'
57
+ }>()
58
+ </script>
59
+
60
+ <template>
61
+ <div>{{ color }}</div>
62
+ </template>
63
+ ```
64
+
65
+ ## 选项
66
+
67
+ ```ts
68
+ import type { ts, Diagnostic } from 'ts-morph'
69
+
70
+ interface TransformWriteFile {
71
+ filePath?: string
72
+ content?: string
73
+ }
74
+
75
+ export interface PluginOptions {
76
+ // 执行的根目录
77
+ // 默认基于 vite 配置的 root 选项
78
+ root?: string
79
+
80
+ // 声明文件的输出目录
81
+ // 默认基于 vite 配置的输出目录
82
+ outputDir?: string
83
+
84
+ // 用于手动设置入口文件的根路径
85
+ // 在计算每个文件的输出路径时将基于该路径
86
+ // 默认为所有文件的最小公共路径
87
+ entryRoot?: string
88
+
89
+ // 提供给 ts-morph Project 初始化的 compilerOptions 选项
90
+ // 默认值: null
91
+ compilerOptions?: ts.CompilerOptions | null
92
+
93
+ // 提供给 ts-morph Project 初始化的 tsconfig.json 路径
94
+ // 插件也会读取 tsconfig.json 的 incldue 和 exclude 选项来解析文件
95
+ // 默认值: 'tsconfig.json'
96
+ tsConfigFilePath?: string
97
+
98
+ // 是否将 '.vue.d.ts' 文件名转换为 '.d.ts'
99
+ // 默认值: false
100
+ cleanVueFileName?: boolean
101
+
102
+ //是否将动态引入转换为静态
103
+ // 当开启打包类型文件时强制为 true
104
+ // eg. 'import('vue').DefineComponent' 转换为 'import { DefineComponent } from "vue"'
105
+ // 默认值: false
106
+ staticImport?: boolean
107
+
108
+ // 手动设置包含路径的 glob
109
+ // 默认基于 tsconfig.json 的 include 选项
110
+ include?: string | string[]
111
+
112
+ // 手动设置排除路径的 glob
113
+ // 默认基于 tsconfig.json 的 exclude 选线,未设置时为 'node_module/**'
114
+ exclude?: string | string[]
115
+
116
+ // 是否生成类型声明入口
117
+ // 当为 true 时会基于 package.json 的 types 字段生成,或者 `${outputDir}/index.d.ts`
118
+ // 当开启打包类型文件时强制为 true
119
+ // 默认值: false
120
+ insertTypesEntry?: boolean
121
+
122
+ // 设置是否在发出类型文件后将其打包
123
+ // 基于 `@microsoft/api-extractor`,由于这开启了一个新的进程,将会消耗一些时间
124
+ // 默认值: false
125
+ rollupTypes?: boolean
126
+
127
+ // 是否将源码里的 .d.ts 文件复制到 outputDir
128
+ // 默认值: true
129
+ copyDtsFiles?: boolean
130
+
131
+ // 出现类型诊断信息时不生成类型文件
132
+ // 默认值: false
133
+ noEmitOnError?: boolean
134
+
135
+ // 是否跳过类型诊断
136
+ // 跳过类型诊断意味着出现错误时不会中断打包进程的执行
137
+ // 但对于出现错误的源文件,将无法生成相应的类型文件
138
+ // 默认值: true
139
+ skipDiagnostics?: boolean
140
+
141
+ // 是否打印类型诊断信息
142
+ // 当跳过类型诊断时该属性将不会生效
143
+ // 默认值: false
144
+ logDiagnostics?: boolean
145
+
146
+ // 获取诊断信息后的钩子
147
+ // 可以根据参数 length 来判断有误类型错误
148
+ // 默认值: () => {}
149
+ afterDiagnostic?: (diagnostics: Diagnostic[]) => void | Promise<void>
150
+
151
+ // 类型声明文件被写入前的钩子
152
+ // 可以在钩子里转换文件路径和文件内容
153
+ // 默认值: () => {}
154
+ beforeWriteFile?: (filePath: string, content: string) => void | TransformWriteFile
155
+
156
+ // 构建后回调钩子
157
+ // 将会在所有类型文件被写入后调用
158
+ // 默认值: () => {}
159
+ afterBuild?: () => void | Promise<void>
160
+ }
161
+ ```
162
+
163
+ ## 示例
164
+
165
+ 克隆项目然后执行下列命令:
166
+
167
+ ```sh
168
+ pnpm run test:e2e
169
+ ```
170
+
171
+ 然后检查 `example/types` 目录。
172
+
173
+ ## 常见问题
174
+
175
+ 此处将收录一些常见的问题并提供一些解决方案。
176
+
177
+ ### 打包后出现类型文件缺失
178
+
179
+ 默认情况下 `skipDiagnostics` 选项的值为 `true`,这意味着打包过程中将跳过类型检查(一些项目通常有 `vue-tsc` 等的类型检查工具),这时如果出现存在类型错误的文件,并且这是错误会中断打包过程,那么这些文件对应的类型文件将不会被生成。
180
+
181
+ 如果您的项目没有依赖外部的类型检查工具,这时候可以您可以设置 `skipDiagnostics: false` 和 `logDiagnostics: true` 来打开插件的诊断与输出功能,这将帮助您检查打包过程中出现的类型错误并将错误信息输出至终端。
182
+
183
+ ### Vue 组件中同时使用了 `script` 和 `setup-script` 后出现类型错误
184
+
185
+ 这通常是由于分别在 `script` 和 `setup-script` 中同时使用了 `defineComponent` 方法导致的。 `vue/compiler-sfc` 为这类文件编译时会将 `script` 中的默认导出结果合并到 `setup-script` 的 `defineComponent` 的参数定义中,而 `defineComponent` 的参数类型与结果类型并不兼容,这一行为将会导致类型错误。
186
+
187
+ 这是一个简单的[示例](https://github.com/qmhc/vite-plugin-dts/blob/main/example/components/BothScripts.vue),您应该将位于 `script` 中的 `defineComponent` 方法移除,直接导出一个原始的对象。
188
+
189
+ ## 授权
190
+
191
+ MIT 授权。
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Plugin } from 'vite';
1
+ import { Plugin, Alias } from 'vite';
2
2
  import { ts, Diagnostic } from 'ts-morph';
3
3
 
4
4
  interface TransformWriteFile {
@@ -9,10 +9,11 @@ interface PluginOptions {
9
9
  include?: string | string[];
10
10
  exclude?: string | string[];
11
11
  root?: string;
12
- outputDir?: string;
12
+ outputDir?: string | string[];
13
13
  entryRoot?: string;
14
14
  compilerOptions?: ts.CompilerOptions | null;
15
15
  tsConfigFilePath?: string;
16
+ aliasesExclude?: Alias['find'][];
16
17
  cleanVueFileName?: boolean;
17
18
  staticImport?: boolean;
18
19
  clearPureImport?: boolean;
package/dist/index.js CHANGED
@@ -299,20 +299,21 @@ function compileVueCode(code) {
299
299
  id: `${index++}`
300
300
  });
301
301
  const classMatch = compiled.content.match(exportDefaultClassRE);
302
+ const plugins = scriptSetup.lang === "ts" ? ["typescript"] : void 0;
302
303
  if (classMatch) {
303
304
  content = compiled.content.replace(exportDefaultClassRE, "\nclass $1") + `
304
305
  const _sfc_main = ${classMatch[1]}`;
305
306
  if (exportDefaultRE.test(content)) {
306
- content = rewriteDefault(compiled.content, "_sfc_main");
307
+ content = rewriteDefault(compiled.content, "_sfc_main", plugins);
307
308
  }
308
309
  } else {
309
- content = rewriteDefault(compiled.content, "_sfc_main");
310
+ content = rewriteDefault(compiled.content, "_sfc_main", plugins);
310
311
  }
311
312
  content = transferSetupPosition(content);
312
313
  content += "\nexport default _sfc_main\n";
313
314
  ext = scriptSetup.lang || "js";
314
315
  } else if (script && script.content) {
315
- content = rewriteDefault(script.content, "_sfc_main");
316
+ content = rewriteDefault(script.content, "_sfc_main", script.lang === "ts" ? ["typescript"] : void 0);
316
317
  content += "\nexport default _sfc_main\n";
317
318
  ext = script.lang || "js";
318
319
  }
@@ -333,7 +334,8 @@ function rollupDeclarationFiles({
333
334
  tsConfigPath,
334
335
  outputDir,
335
336
  entryPath,
336
- fileName
337
+ fileName,
338
+ compilerOptions
337
339
  }) {
338
340
  const configObjectFullPath = (0, import_path3.resolve)(root, "api-extractor.json");
339
341
  const packageJsonLookup = new import_node_core_library.PackageJsonLookup();
@@ -346,7 +348,8 @@ function rollupDeclarationFiles({
346
348
  projectFolder: root,
347
349
  mainEntryPointFilePath: entryPath,
348
350
  compiler: {
349
- tsconfigFilePath: tsConfigPath
351
+ tsconfigFilePath: tsConfigPath,
352
+ overrideTsconfig: compilerOptions
350
353
  },
351
354
  apiReport: {
352
355
  enabled: false,
@@ -418,6 +421,7 @@ function dtsPlugin(options = {}) {
418
421
  var _a, _b;
419
422
  const {
420
423
  tsConfigFilePath = "tsconfig.json",
424
+ aliasesExclude = [],
421
425
  cleanVueFileName = false,
422
426
  staticImport = false,
423
427
  clearPureImport = true,
@@ -434,14 +438,13 @@ function dtsPlugin(options = {}) {
434
438
  const compilerOptions = (_a = options.compilerOptions) != null ? _a : {};
435
439
  let root;
436
440
  let entryRoot = (_b = options.entryRoot) != null ? _b : "";
437
- let libName;
438
441
  let indexName;
439
442
  let aliases;
440
443
  let entries;
441
444
  let logger;
442
445
  let project;
443
446
  let tsConfigPath;
444
- let outputDir;
447
+ let outputDirs;
445
448
  let isBundle = false;
446
449
  const sourceDtsFiles = /* @__PURE__ */ new Set();
447
450
  let hasJsVue = false;
@@ -451,10 +454,10 @@ function dtsPlugin(options = {}) {
451
454
  apply: "build",
452
455
  enforce: "pre",
453
456
  config(config) {
454
- var _a2;
457
+ var _a2, _b2;
455
458
  if (isBundle)
456
459
  return;
457
- const aliasOptions = (_a2 = config.resolve && config.resolve.alias) != null ? _a2 : [];
460
+ const aliasOptions = (_b2 = (_a2 = config == null ? void 0 : config.resolve) == null ? void 0 : _a2.alias) != null ? _b2 : [];
458
461
  if (isNativeObj(aliasOptions)) {
459
462
  aliases = Object.entries(aliasOptions).map(([key, value]) => {
460
463
  return { find: key, replacement: value };
@@ -462,6 +465,12 @@ function dtsPlugin(options = {}) {
462
465
  } else {
463
466
  aliases = ensureArray(aliasOptions);
464
467
  }
468
+ if (aliasesExclude.length > 0) {
469
+ aliases = aliases.filter(({ find }) => !aliasesExclude.some((alias) => {
470
+ var _a3;
471
+ return alias && (isRegExp(find) ? find.toString() === alias.toString() : isRegExp(alias) ? (_a3 = find.match(alias)) == null ? void 0 : _a3[0] : find === alias);
472
+ }));
473
+ }
465
474
  },
466
475
  configResolved(config) {
467
476
  var _a2, _b2, _c;
@@ -472,11 +481,9 @@ function dtsPlugin(options = {}) {
472
481
  logger.warn(import_chalk.default.yellow(`
473
482
  ${import_chalk.default.cyan("[vite:dts]")} You building not a library that may not need to generate declaration files.
474
483
  `));
475
- libName = "_default";
476
484
  indexName = defaultIndex;
477
485
  } else {
478
486
  const filename = (_a2 = config.build.lib.fileName) != null ? _a2 : defaultIndex;
479
- libName = config.build.lib.name || "_default";
480
487
  indexName = typeof filename === "string" ? filename : filename("es");
481
488
  if (!dtsRE2.test(indexName)) {
482
489
  indexName = `${tjsRE.test(indexName) ? indexName.replace(tjsRE, "") : indexName}.d.ts`;
@@ -484,8 +491,8 @@ ${import_chalk.default.cyan("[vite:dts]")} You building not a library that may n
484
491
  }
485
492
  root = ensureAbsolute((_b2 = options.root) != null ? _b2 : "", config.root);
486
493
  tsConfigPath = ensureAbsolute(tsConfigFilePath, root);
487
- outputDir = options.outputDir ? ensureAbsolute(options.outputDir, root) : ensureAbsolute(config.build.outDir, root);
488
- if (!outputDir) {
494
+ outputDirs = options.outputDir ? ensureArray(options.outputDir).map((d) => ensureAbsolute(d, root)) : [ensureAbsolute(config.build.outDir, root)];
495
+ if (!outputDirs) {
489
496
  logger.error(import_chalk.default.red(`
490
497
  ${import_chalk.default.cyan("[vite:dts]")} Can not resolve declaration directory, please check your vite config and plugin options.
491
498
  `));
@@ -540,7 +547,7 @@ ${import_chalk.default.cyan("[vite:dts]")} Can not resolve declaration directory
540
547
  },
541
548
  async closeBundle() {
542
549
  var _a2, _b2, _c, _d, _e, _f;
543
- if (!outputDir || !project || isBundle)
550
+ if (!outputDirs || !project || isBundle)
544
551
  return;
545
552
  logger.info(import_chalk.default.green(`
546
553
  ${logPrefix} Start generate declaration files...`));
@@ -597,7 +604,7 @@ ${logPrefix} Start generate declaration files...`));
597
604
  }));
598
605
  const service = project.getLanguageService();
599
606
  const outputFiles = project.getSourceFiles().map((sourceFile) => service.getEmitOutput(sourceFile, true).getOutputFiles().map((outputFile) => ({
600
- path: outputFile.getFilePath(),
607
+ path: (0, import_vite2.normalizePath)((0, import_path4.resolve)(root, outputFile.compilerObject.name)),
601
608
  content: outputFile.getText()
602
609
  }))).flat().concat(dtsOutputFiles);
603
610
  bundleDebug("emit");
@@ -606,6 +613,7 @@ ${logPrefix} Start generate declaration files...`));
606
613
  }
607
614
  entryRoot = ensureAbsolute(entryRoot, root);
608
615
  const wroteFiles = /* @__PURE__ */ new Set();
616
+ const outputDir = outputDirs[0];
609
617
  await runParallel(import_os.default.cpus().length, outputFiles, async (outputFile) => {
610
618
  var _a3, _b3;
611
619
  let filePath = outputFile.path;
@@ -628,22 +636,21 @@ ${logPrefix} Start generate declaration files...`));
628
636
  }
629
637
  }
630
638
  await import_fs_extra.default.mkdir((0, import_path4.dirname)(filePath), { recursive: true });
631
- await import_fs_extra.default.writeFile(filePath, cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content, "utf8");
639
+ await import_fs_extra.default.writeFile(filePath, cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content, "utf-8");
632
640
  wroteFiles.add((0, import_vite2.normalizePath)(filePath));
633
641
  });
634
642
  bundleDebug("output");
635
643
  if (insertTypesEntry || rollupTypes) {
636
644
  const pkgPath = (0, import_path4.resolve)(root, "package.json");
637
645
  const pkg = import_fs_extra.default.existsSync(pkgPath) ? JSON.parse(await import_fs_extra.default.readFile(pkgPath, "utf-8")) : {};
638
- let typesPath = pkg.types ? (0, import_path4.resolve)(root, pkg.types) : (0, import_path4.resolve)(outputDir, indexName);
646
+ const types = pkg.types || pkg.typings;
647
+ let typesPath = types ? (0, import_path4.resolve)(root, types) : (0, import_path4.resolve)(outputDir, indexName);
639
648
  if (!import_fs_extra.default.existsSync(typesPath)) {
640
649
  const entry = entries[0];
641
650
  let filePath = (0, import_vite2.normalizePath)((0, import_path4.relative)((0, import_path4.dirname)(typesPath), (0, import_path4.resolve)(outputDir, (0, import_path4.relative)(entryRoot, entry))));
642
651
  filePath = filePath.replace(tsRE, "");
643
652
  filePath = fullRelativeRE.test(filePath) ? filePath : `./${filePath}`;
644
- let content = `import ${libName} from '${filePath}'
645
- export default ${libName}
646
- export * from '${filePath}'
653
+ let content = `export * from '${filePath}'
647
654
  `;
648
655
  if (typeof beforeWriteFile === "function") {
649
656
  const result = beforeWriteFile(typesPath, content);
@@ -660,21 +667,39 @@ export * from '${filePath}'
660
667
  rollupDeclarationFiles({
661
668
  root,
662
669
  tsConfigPath,
670
+ compilerOptions,
663
671
  outputDir,
664
672
  entryPath: typesPath,
665
673
  fileName: (0, import_path4.basename)(typesPath)
666
674
  });
667
- wroteFiles.delete((0, import_vite2.normalizePath)(typesPath));
675
+ const wroteFile = (0, import_vite2.normalizePath)(typesPath);
676
+ wroteFiles.delete(wroteFile);
668
677
  await runParallel(import_os.default.cpus().length, Array.from(wroteFiles), (f) => import_fs_extra.default.unlink(f));
669
678
  removeDirIfEmpty(outputDir);
679
+ wroteFiles.clear();
680
+ wroteFiles.add(wroteFile);
670
681
  if (copyDtsFiles) {
671
682
  await runParallel(import_os.default.cpus().length, dtsOutputFiles, async ({ path, content }) => {
672
- await import_fs_extra.default.writeFile((0, import_path4.resolve)(outputDir, (0, import_path4.basename)(path)), content, "utf8");
683
+ const filePath = (0, import_path4.resolve)(outputDir, (0, import_path4.basename)(path));
684
+ await import_fs_extra.default.writeFile(filePath, content, "utf-8");
685
+ wroteFiles.add((0, import_vite2.normalizePath)(filePath));
673
686
  });
674
687
  }
675
688
  bundleDebug("rollup");
676
689
  }
677
690
  }
691
+ if (outputDirs.length > 1) {
692
+ const dirs = outputDirs.slice(1);
693
+ await runParallel(import_os.default.cpus().length, Array.from(wroteFiles), async (wroteFile) => {
694
+ const relativePath = (0, import_path4.relative)(outputDir, wroteFile);
695
+ const content = await import_fs_extra.default.readFile(wroteFile, "utf-8");
696
+ await Promise.all(dirs.map(async (dir) => {
697
+ const filePath = (0, import_path4.resolve)(dir, relativePath);
698
+ await import_fs_extra.default.mkdir((0, import_path4.dirname)(filePath), { recursive: true });
699
+ await import_fs_extra.default.writeFile(filePath, content, "utf-8");
700
+ }));
701
+ });
702
+ }
678
703
  if (typeof afterBuild === "function") {
679
704
  const result = afterBuild();
680
705
  isPromise(result) && await result;
package/dist/index.mjs CHANGED
@@ -278,20 +278,21 @@ function compileVueCode(code) {
278
278
  id: `${index++}`
279
279
  });
280
280
  const classMatch = compiled.content.match(exportDefaultClassRE);
281
+ const plugins = scriptSetup.lang === "ts" ? ["typescript"] : void 0;
281
282
  if (classMatch) {
282
283
  content = compiled.content.replace(exportDefaultClassRE, "\nclass $1") + `
283
284
  const _sfc_main = ${classMatch[1]}`;
284
285
  if (exportDefaultRE.test(content)) {
285
- content = rewriteDefault(compiled.content, "_sfc_main");
286
+ content = rewriteDefault(compiled.content, "_sfc_main", plugins);
286
287
  }
287
288
  } else {
288
- content = rewriteDefault(compiled.content, "_sfc_main");
289
+ content = rewriteDefault(compiled.content, "_sfc_main", plugins);
289
290
  }
290
291
  content = transferSetupPosition(content);
291
292
  content += "\nexport default _sfc_main\n";
292
293
  ext = scriptSetup.lang || "js";
293
294
  } else if (script && script.content) {
294
- content = rewriteDefault(script.content, "_sfc_main");
295
+ content = rewriteDefault(script.content, "_sfc_main", script.lang === "ts" ? ["typescript"] : void 0);
295
296
  content += "\nexport default _sfc_main\n";
296
297
  ext = script.lang || "js";
297
298
  }
@@ -315,7 +316,8 @@ function rollupDeclarationFiles({
315
316
  tsConfigPath,
316
317
  outputDir,
317
318
  entryPath,
318
- fileName
319
+ fileName,
320
+ compilerOptions
319
321
  }) {
320
322
  const configObjectFullPath = resolve2(root, "api-extractor.json");
321
323
  const packageJsonLookup = new PackageJsonLookup();
@@ -328,7 +330,8 @@ function rollupDeclarationFiles({
328
330
  projectFolder: root,
329
331
  mainEntryPointFilePath: entryPath,
330
332
  compiler: {
331
- tsconfigFilePath: tsConfigPath
333
+ tsconfigFilePath: tsConfigPath,
334
+ overrideTsconfig: compilerOptions
332
335
  },
333
336
  apiReport: {
334
337
  enabled: false,
@@ -400,6 +403,7 @@ function dtsPlugin(options = {}) {
400
403
  var _a, _b;
401
404
  const {
402
405
  tsConfigFilePath = "tsconfig.json",
406
+ aliasesExclude = [],
403
407
  cleanVueFileName = false,
404
408
  staticImport = false,
405
409
  clearPureImport = true,
@@ -416,14 +420,13 @@ function dtsPlugin(options = {}) {
416
420
  const compilerOptions = (_a = options.compilerOptions) != null ? _a : {};
417
421
  let root;
418
422
  let entryRoot = (_b = options.entryRoot) != null ? _b : "";
419
- let libName;
420
423
  let indexName;
421
424
  let aliases;
422
425
  let entries;
423
426
  let logger;
424
427
  let project;
425
428
  let tsConfigPath;
426
- let outputDir;
429
+ let outputDirs;
427
430
  let isBundle = false;
428
431
  const sourceDtsFiles = /* @__PURE__ */ new Set();
429
432
  let hasJsVue = false;
@@ -433,10 +436,10 @@ function dtsPlugin(options = {}) {
433
436
  apply: "build",
434
437
  enforce: "pre",
435
438
  config(config) {
436
- var _a2;
439
+ var _a2, _b2;
437
440
  if (isBundle)
438
441
  return;
439
- const aliasOptions = (_a2 = config.resolve && config.resolve.alias) != null ? _a2 : [];
442
+ const aliasOptions = (_b2 = (_a2 = config == null ? void 0 : config.resolve) == null ? void 0 : _a2.alias) != null ? _b2 : [];
440
443
  if (isNativeObj(aliasOptions)) {
441
444
  aliases = Object.entries(aliasOptions).map(([key, value]) => {
442
445
  return { find: key, replacement: value };
@@ -444,6 +447,12 @@ function dtsPlugin(options = {}) {
444
447
  } else {
445
448
  aliases = ensureArray(aliasOptions);
446
449
  }
450
+ if (aliasesExclude.length > 0) {
451
+ aliases = aliases.filter(({ find }) => !aliasesExclude.some((alias) => {
452
+ var _a3;
453
+ return alias && (isRegExp(find) ? find.toString() === alias.toString() : isRegExp(alias) ? (_a3 = find.match(alias)) == null ? void 0 : _a3[0] : find === alias);
454
+ }));
455
+ }
447
456
  },
448
457
  configResolved(config) {
449
458
  var _a2, _b2, _c;
@@ -454,11 +463,9 @@ function dtsPlugin(options = {}) {
454
463
  logger.warn(chalk.yellow(`
455
464
  ${chalk.cyan("[vite:dts]")} You building not a library that may not need to generate declaration files.
456
465
  `));
457
- libName = "_default";
458
466
  indexName = defaultIndex;
459
467
  } else {
460
468
  const filename = (_a2 = config.build.lib.fileName) != null ? _a2 : defaultIndex;
461
- libName = config.build.lib.name || "_default";
462
469
  indexName = typeof filename === "string" ? filename : filename("es");
463
470
  if (!dtsRE2.test(indexName)) {
464
471
  indexName = `${tjsRE.test(indexName) ? indexName.replace(tjsRE, "") : indexName}.d.ts`;
@@ -466,8 +473,8 @@ ${chalk.cyan("[vite:dts]")} You building not a library that may not need to gene
466
473
  }
467
474
  root = ensureAbsolute((_b2 = options.root) != null ? _b2 : "", config.root);
468
475
  tsConfigPath = ensureAbsolute(tsConfigFilePath, root);
469
- outputDir = options.outputDir ? ensureAbsolute(options.outputDir, root) : ensureAbsolute(config.build.outDir, root);
470
- if (!outputDir) {
476
+ outputDirs = options.outputDir ? ensureArray(options.outputDir).map((d) => ensureAbsolute(d, root)) : [ensureAbsolute(config.build.outDir, root)];
477
+ if (!outputDirs) {
471
478
  logger.error(chalk.red(`
472
479
  ${chalk.cyan("[vite:dts]")} Can not resolve declaration directory, please check your vite config and plugin options.
473
480
  `));
@@ -522,7 +529,7 @@ ${chalk.cyan("[vite:dts]")} Can not resolve declaration directory, please check
522
529
  },
523
530
  async closeBundle() {
524
531
  var _a2, _b2, _c, _d, _e, _f;
525
- if (!outputDir || !project || isBundle)
532
+ if (!outputDirs || !project || isBundle)
526
533
  return;
527
534
  logger.info(chalk.green(`
528
535
  ${logPrefix} Start generate declaration files...`));
@@ -579,7 +586,7 @@ ${logPrefix} Start generate declaration files...`));
579
586
  }));
580
587
  const service = project.getLanguageService();
581
588
  const outputFiles = project.getSourceFiles().map((sourceFile) => service.getEmitOutput(sourceFile, true).getOutputFiles().map((outputFile) => ({
582
- path: outputFile.getFilePath(),
589
+ path: normalizePath2(resolve3(root, outputFile.compilerObject.name)),
583
590
  content: outputFile.getText()
584
591
  }))).flat().concat(dtsOutputFiles);
585
592
  bundleDebug("emit");
@@ -588,6 +595,7 @@ ${logPrefix} Start generate declaration files...`));
588
595
  }
589
596
  entryRoot = ensureAbsolute(entryRoot, root);
590
597
  const wroteFiles = /* @__PURE__ */ new Set();
598
+ const outputDir = outputDirs[0];
591
599
  await runParallel(os.cpus().length, outputFiles, async (outputFile) => {
592
600
  var _a3, _b3;
593
601
  let filePath = outputFile.path;
@@ -610,22 +618,21 @@ ${logPrefix} Start generate declaration files...`));
610
618
  }
611
619
  }
612
620
  await fs.mkdir(dirname3(filePath), { recursive: true });
613
- await fs.writeFile(filePath, cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content, "utf8");
621
+ await fs.writeFile(filePath, cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content, "utf-8");
614
622
  wroteFiles.add(normalizePath2(filePath));
615
623
  });
616
624
  bundleDebug("output");
617
625
  if (insertTypesEntry || rollupTypes) {
618
626
  const pkgPath = resolve3(root, "package.json");
619
627
  const pkg = fs.existsSync(pkgPath) ? JSON.parse(await fs.readFile(pkgPath, "utf-8")) : {};
620
- let typesPath = pkg.types ? resolve3(root, pkg.types) : resolve3(outputDir, indexName);
628
+ const types = pkg.types || pkg.typings;
629
+ let typesPath = types ? resolve3(root, types) : resolve3(outputDir, indexName);
621
630
  if (!fs.existsSync(typesPath)) {
622
631
  const entry = entries[0];
623
632
  let filePath = normalizePath2(relative2(dirname3(typesPath), resolve3(outputDir, relative2(entryRoot, entry))));
624
633
  filePath = filePath.replace(tsRE, "");
625
634
  filePath = fullRelativeRE.test(filePath) ? filePath : `./${filePath}`;
626
- let content = `import ${libName} from '${filePath}'
627
- export default ${libName}
628
- export * from '${filePath}'
635
+ let content = `export * from '${filePath}'
629
636
  `;
630
637
  if (typeof beforeWriteFile === "function") {
631
638
  const result = beforeWriteFile(typesPath, content);
@@ -642,21 +649,39 @@ export * from '${filePath}'
642
649
  rollupDeclarationFiles({
643
650
  root,
644
651
  tsConfigPath,
652
+ compilerOptions,
645
653
  outputDir,
646
654
  entryPath: typesPath,
647
655
  fileName: basename(typesPath)
648
656
  });
649
- wroteFiles.delete(normalizePath2(typesPath));
657
+ const wroteFile = normalizePath2(typesPath);
658
+ wroteFiles.delete(wroteFile);
650
659
  await runParallel(os.cpus().length, Array.from(wroteFiles), (f) => fs.unlink(f));
651
660
  removeDirIfEmpty(outputDir);
661
+ wroteFiles.clear();
662
+ wroteFiles.add(wroteFile);
652
663
  if (copyDtsFiles) {
653
664
  await runParallel(os.cpus().length, dtsOutputFiles, async ({ path, content }) => {
654
- await fs.writeFile(resolve3(outputDir, basename(path)), content, "utf8");
665
+ const filePath = resolve3(outputDir, basename(path));
666
+ await fs.writeFile(filePath, content, "utf-8");
667
+ wroteFiles.add(normalizePath2(filePath));
655
668
  });
656
669
  }
657
670
  bundleDebug("rollup");
658
671
  }
659
672
  }
673
+ if (outputDirs.length > 1) {
674
+ const dirs = outputDirs.slice(1);
675
+ await runParallel(os.cpus().length, Array.from(wroteFiles), async (wroteFile) => {
676
+ const relativePath = relative2(outputDir, wroteFile);
677
+ const content = await fs.readFile(wroteFile, "utf-8");
678
+ await Promise.all(dirs.map(async (dir) => {
679
+ const filePath = resolve3(dir, relativePath);
680
+ await fs.mkdir(dirname3(filePath), { recursive: true });
681
+ await fs.writeFile(filePath, content, "utf-8");
682
+ }));
683
+ });
684
+ }
660
685
  if (typeof afterBuild === "function") {
661
686
  const result = afterBuild();
662
687
  isPromise(result) && await result;
package/package.json CHANGED
@@ -93,5 +93,5 @@
93
93
  "test:e2e": "cd example && cross-env DEBUG=\"vite-plugin-dts:bundle\" vite build"
94
94
  },
95
95
  "types": "dist/index.d.ts",
96
- "version": "1.1.1"
96
+ "version": "1.3.0"
97
97
  }