vite-plugin-dts 1.3.0 → 1.4.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
@@ -2,7 +2,7 @@
2
2
 
3
3
  **English** | [中文](./README.zh-CN.md)
4
4
 
5
- A vite plugin that generates declaration files (`*.d.ts`) from `.ts` or `.vue` source files when using vite in [library mode](https://vitejs.dev/guide/build.html#library-mode).
5
+ A vite plugin that generates declaration files (`*.d.ts`) from `.ts(x)` or `.vue` source files when using vite in [library mode](https://vitejs.dev/guide/build.html#library-mode).
6
6
 
7
7
  ## Install
8
8
 
@@ -79,8 +79,9 @@ export interface PluginOptions {
79
79
  root?: string
80
80
 
81
81
  // Declaration files output directory
82
+ // Can be specified a array to output to multiple directories
82
83
  // Defaults base on your vite config output options
83
- outputDir?: string
84
+ outputDir?: string | string[]
84
85
 
85
86
  // Manually set the root path of the entry files
86
87
  // The output path of each file will be caculated base on it
@@ -187,6 +188,21 @@ This is usually caused by using `defineComponent` function in both `script` and
187
188
 
188
189
  Here is a simple [example](https://github.com/qmhc/vite-plugin-dts/blob/main/example/components/BothScripts.vue), you should remove the `defineComponent` which in `script` and export a native object directly.
189
190
 
191
+ ### Take errors that unable to infer types from packages which under `node_modules`
192
+
193
+ This is a exist issue when TypeScript inferring types from packages which under `node_modules` through soft links (pnpm), you can refer to this [issue](https://github.com/microsoft/TypeScript/issues/42873). Currently has a workaround that add `baseUrl` to your `tsconfig.json` and specify the `paths` for these packages:
194
+
195
+ ```json
196
+ {
197
+ "compilerOptions": {
198
+ "baseUrl": ".",
199
+ "paths": {
200
+ "third-lib": ["node_modules/third-lib"]
201
+ }
202
+ }
203
+ }
204
+ ```
205
+
190
206
  ## License
191
207
 
192
208
  MIT License.
package/README.zh-CN.md CHANGED
@@ -1,191 +1,207 @@
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 授权。
1
+ # vite-plugin-dts
2
+
3
+ **中文** | [English](./README.md)
4
+
5
+ 一款用于在 [库模式](https://cn.vitejs.dev/guide/build.html#library-mode) 中,从 `.ts(x)` 或 `.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
+ // 可以指定一个数组来输出到多个目录中
82
+ // 默认基于 vite 配置的输出目录
83
+ outputDir?: string | string[]
84
+
85
+ // 用于手动设置入口文件的根路径
86
+ // 在计算每个文件的输出路径时将基于该路径
87
+ // 默认为所有文件的最小公共路径
88
+ entryRoot?: string
89
+
90
+ // 提供给 ts-morph Project 初始化的 compilerOptions 选项
91
+ // 默认值: null
92
+ compilerOptions?: ts.CompilerOptions | null
93
+
94
+ // 提供给 ts-morph Project 初始化的 tsconfig.json 路径
95
+ // 插件也会读取 tsconfig.json 的 incldue 和 exclude 选项来解析文件
96
+ // 默认值: 'tsconfig.json'
97
+ tsConfigFilePath?: string
98
+
99
+ // 是否将 '.vue.d.ts' 文件名转换为 '.d.ts'
100
+ // 默认值: false
101
+ cleanVueFileName?: boolean
102
+
103
+ //是否将动态引入转换为静态
104
+ // 当开启打包类型文件时强制为 true
105
+ // eg. 'import('vue').DefineComponent' 转换为 'import { DefineComponent } from "vue"'
106
+ // 默认值: false
107
+ staticImport?: boolean
108
+
109
+ // 手动设置包含路径的 glob
110
+ // 默认基于 tsconfig.json 的 include 选项
111
+ include?: string | string[]
112
+
113
+ // 手动设置排除路径的 glob
114
+ // 默认基于 tsconfig.json 的 exclude 选线,未设置时为 'node_module/**'
115
+ exclude?: string | string[]
116
+
117
+ // 是否生成类型声明入口
118
+ // 当为 true 时会基于 package.json 的 types 字段生成,或者 `${outputDir}/index.d.ts`
119
+ // 当开启打包类型文件时强制为 true
120
+ // 默认值: false
121
+ insertTypesEntry?: boolean
122
+
123
+ // 设置是否在发出类型文件后将其打包
124
+ // 基于 `@microsoft/api-extractor`,由于这开启了一个新的进程,将会消耗一些时间
125
+ // 默认值: false
126
+ rollupTypes?: boolean
127
+
128
+ // 是否将源码里的 .d.ts 文件复制到 outputDir
129
+ // 默认值: true
130
+ copyDtsFiles?: boolean
131
+
132
+ // 出现类型诊断信息时不生成类型文件
133
+ // 默认值: false
134
+ noEmitOnError?: boolean
135
+
136
+ // 是否跳过类型诊断
137
+ // 跳过类型诊断意味着出现错误时不会中断打包进程的执行
138
+ // 但对于出现错误的源文件,将无法生成相应的类型文件
139
+ // 默认值: true
140
+ skipDiagnostics?: boolean
141
+
142
+ // 是否打印类型诊断信息
143
+ // 当跳过类型诊断时该属性将不会生效
144
+ // 默认值: false
145
+ logDiagnostics?: boolean
146
+
147
+ // 获取诊断信息后的钩子
148
+ // 可以根据参数 length 来判断有误类型错误
149
+ // 默认值: () => {}
150
+ afterDiagnostic?: (diagnostics: Diagnostic[]) => void | Promise<void>
151
+
152
+ // 类型声明文件被写入前的钩子
153
+ // 可以在钩子里转换文件路径和文件内容
154
+ // 默认值: () => {}
155
+ beforeWriteFile?: (filePath: string, content: string) => void | TransformWriteFile
156
+
157
+ // 构建后回调钩子
158
+ // 将会在所有类型文件被写入后调用
159
+ // 默认值: () => {}
160
+ afterBuild?: () => void | Promise<void>
161
+ }
162
+ ```
163
+
164
+ ## 示例
165
+
166
+ 克隆项目然后执行下列命令:
167
+
168
+ ```sh
169
+ pnpm run test:e2e
170
+ ```
171
+
172
+ 然后检查 `example/types` 目录。
173
+
174
+ ## 常见问题
175
+
176
+ 此处将收录一些常见的问题并提供一些解决方案。
177
+
178
+ ### 打包后出现类型文件缺失
179
+
180
+ 默认情况下 `skipDiagnostics` 选项的值为 `true`,这意味着打包过程中将跳过类型检查(一些项目通常有 `vue-tsc` 等的类型检查工具),这时如果出现存在类型错误的文件,并且这是错误会中断打包过程,那么这些文件对应的类型文件将不会被生成。
181
+
182
+ 如果您的项目没有依赖外部的类型检查工具,这时候可以您可以设置 `skipDiagnostics: false` 和 `logDiagnostics: true` 来打开插件的诊断与输出功能,这将帮助您检查打包过程中出现的类型错误并将错误信息输出至终端。
183
+
184
+ ### Vue 组件中同时使用了 `script` 和 `setup-script` 后出现类型错误
185
+
186
+ 这通常是由于分别在 `script` 和 `setup-script` 中同时使用了 `defineComponent` 方法导致的。 `vue/compiler-sfc` 为这类文件编译时会将 `script` 中的默认导出结果合并到 `setup-script` 的 `defineComponent` 的参数定义中,而 `defineComponent` 的参数类型与结果类型并不兼容,这一行为将会导致类型错误。
187
+
188
+ 这是一个简单的[示例](https://github.com/qmhc/vite-plugin-dts/blob/main/example/components/BothScripts.vue),您应该将位于 `script` 中的 `defineComponent` 方法移除,直接导出一个原始的对象。
189
+
190
+ ### 打包时出现了无法从 `node_modules` 的包中推断类型的错误
191
+
192
+ 这是 TypeScript 通过软链接 (pnpm) 读取 `node_modules` 中过的类型时会出现的一个已知的问题,可以参考这个 [issue](https://github.com/microsoft/TypeScript/issues/42873),目前已有的一个解决方案,在你的 `tsconfig.json` 中添加 `baseUrl` 以及在 `paths` 添加这些包的路径:
193
+
194
+ ```json
195
+ {
196
+ "compilerOptions": {
197
+ "baseUrl": ".",
198
+ "paths": {
199
+ "third-lib": ["node_modules/third-lib"]
200
+ }
201
+ }
202
+ }
203
+ ```
204
+
205
+ ## 授权
206
+
207
+ MIT 授权。
package/dist/index.js CHANGED
@@ -256,9 +256,11 @@ function transferSetupPosition(content) {
256
256
  // src/compile.ts
257
257
  var exportDefaultRE = /export\s+default/;
258
258
  var exportDefaultClassRE = /(?:(?:^|\n|;)\s*)export\s+default\s+class\s+([\w$]+)/;
259
+ var noScriptContent = "import { defineComponent } from 'vue'\nexport default defineComponent({})";
259
260
  var index = 1;
260
261
  var compileRoot = null;
261
262
  var compiler;
263
+ var vue;
262
264
  function requireCompiler() {
263
265
  if (!compiler) {
264
266
  if (compileRoot) {
@@ -281,15 +283,43 @@ function requireCompiler() {
281
283
  }
282
284
  return compiler;
283
285
  }
286
+ function isVue3() {
287
+ if (!vue) {
288
+ if (compileRoot) {
289
+ try {
290
+ vue = require(require.resolve("vue", { paths: [compileRoot] }));
291
+ } catch (e) {
292
+ }
293
+ }
294
+ if (!vue) {
295
+ try {
296
+ vue = require("vue");
297
+ } catch (e) {
298
+ throw new Error("vue is not present in the dependency tree.\n");
299
+ }
300
+ }
301
+ }
302
+ return vue.version.startsWith("3");
303
+ }
284
304
  function setCompileRoot(root) {
285
305
  if (root && root !== compileRoot) {
286
306
  compileRoot = root;
287
307
  compiler = null;
288
308
  }
289
309
  }
310
+ function parseCode(code) {
311
+ const { parse } = requireCompiler();
312
+ let descriptor;
313
+ if (isVue3()) {
314
+ descriptor = parse(code).descriptor;
315
+ } else {
316
+ descriptor = parse({ source: code });
317
+ }
318
+ return descriptor;
319
+ }
290
320
  function compileVueCode(code) {
291
- const { parse, compileScript, rewriteDefault } = requireCompiler();
292
- const { descriptor } = parse(code);
321
+ const { compileScript, rewriteDefault } = requireCompiler();
322
+ const descriptor = parseCode(code);
293
323
  const { script, scriptSetup } = descriptor;
294
324
  let content = null;
295
325
  let ext = null;
@@ -317,6 +347,9 @@ const _sfc_main = ${classMatch[1]}`;
317
347
  content += "\nexport default _sfc_main\n";
318
348
  ext = script.lang || "js";
319
349
  }
350
+ } else {
351
+ content = noScriptContent;
352
+ ext = "ts";
320
353
  }
321
354
  return { content, ext };
322
355
  }
@@ -438,6 +471,7 @@ function dtsPlugin(options = {}) {
438
471
  const compilerOptions = (_a = options.compilerOptions) != null ? _a : {};
439
472
  let root;
440
473
  let entryRoot = (_b = options.entryRoot) != null ? _b : "";
474
+ let libName;
441
475
  let indexName;
442
476
  let aliases;
443
477
  let entries;
@@ -481,9 +515,11 @@ function dtsPlugin(options = {}) {
481
515
  logger.warn(import_chalk.default.yellow(`
482
516
  ${import_chalk.default.cyan("[vite:dts]")} You building not a library that may not need to generate declaration files.
483
517
  `));
518
+ libName = "_default";
484
519
  indexName = defaultIndex;
485
520
  } else {
486
521
  const filename = (_a2 = config.build.lib.fileName) != null ? _a2 : defaultIndex;
522
+ libName = config.build.lib.name || "_default";
487
523
  indexName = typeof filename === "string" ? filename : filename("es");
488
524
  if (!dtsRE2.test(indexName)) {
489
525
  indexName = `${tjsRE.test(indexName) ? indexName.replace(tjsRE, "") : indexName}.d.ts`;
@@ -546,7 +582,7 @@ ${import_chalk.default.cyan("[vite:dts]")} Can not resolve declaration directory
546
582
  }
547
583
  },
548
584
  async closeBundle() {
549
- var _a2, _b2, _c, _d, _e, _f;
585
+ var _a2, _b2, _c, _d, _e, _f, _g, _h, _i;
550
586
  if (!outputDirs || !project || isBundle)
551
587
  return;
552
588
  logger.info(import_chalk.default.green(`
@@ -556,15 +592,17 @@ ${logPrefix} Start generate declaration files...`));
556
592
  sourceDtsFiles.clear();
557
593
  const startTime = Date.now();
558
594
  const tsConfig = (_a2 = (0, import_typescript.readConfigFile)(tsConfigPath, project.getFileSystem().readFileSync).config) != null ? _a2 : {};
559
- const include = (_c = (_b2 = options.include) != null ? _b2 : tsConfig.include) != null ? _c : "**/*";
560
- const exclude = (_d = options.exclude) != null ? _d : tsConfig.exclude;
595
+ const parentTsConfigPath = tsConfig.extends && ensureAbsolute(tsConfig.extends, root);
596
+ const parentTsConfig = parentTsConfigPath ? (0, import_typescript.readConfigFile)(parentTsConfigPath, project.getFileSystem().readFileSync).config : {};
597
+ const include = (_d = (_c = (_b2 = options.include) != null ? _b2 : tsConfig.include) != null ? _c : parentTsConfig.include) != null ? _d : "**/*";
598
+ const exclude = (_g = (_f = (_e = options.exclude) != null ? _e : tsConfig.exclude) != null ? _f : parentTsConfig.exclude) != null ? _g : "node_modules/**";
561
599
  bundleDebug("read config");
562
600
  const includedFileSet = /* @__PURE__ */ new Set();
563
601
  if (include && include.length) {
564
602
  const files = await (0, import_fast_glob.default)(ensureArray(include).map(normalizeGlob), {
565
603
  cwd: root,
566
604
  absolute: true,
567
- ignore: ensureArray(exclude != null ? exclude : ["node_modules/**"]).map(normalizeGlob)
605
+ ignore: ensureArray(exclude).map(normalizeGlob)
568
606
  });
569
607
  files.forEach((file) => {
570
608
  if (dtsRE2.test(file)) {
@@ -647,19 +685,29 @@ ${logPrefix} Start generate declaration files...`));
647
685
  let typesPath = types ? (0, import_path4.resolve)(root, types) : (0, import_path4.resolve)(outputDir, indexName);
648
686
  if (!import_fs_extra.default.existsSync(typesPath)) {
649
687
  const entry = entries[0];
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))));
651
- filePath = filePath.replace(tsRE, "");
688
+ const outputIndex = (0, import_path4.resolve)(outputDir, (0, import_path4.relative)(entryRoot, entry.replace(tsRE, ".d.ts")));
689
+ let filePath = (0, import_vite2.normalizePath)((0, import_path4.relative)((0, import_path4.dirname)(typesPath), outputIndex));
690
+ filePath = filePath.replace(dtsRE2, "");
652
691
  filePath = fullRelativeRE.test(filePath) ? filePath : `./${filePath}`;
653
692
  let content = `export * from '${filePath}'
654
693
  `;
694
+ if (import_fs_extra.default.existsSync(outputIndex)) {
695
+ const entryCodes = await import_fs_extra.default.readFile(outputIndex, "utf-8");
696
+ if (entryCodes.includes("export default")) {
697
+ content += `import ${libName} from '${filePath}'
698
+ export default ${libName}
699
+ `;
700
+ }
701
+ }
655
702
  if (typeof beforeWriteFile === "function") {
656
703
  const result = beforeWriteFile(typesPath, content);
657
704
  if (result && isNativeObj(result)) {
658
- typesPath = (_e = result.filePath) != null ? _e : typesPath;
659
- content = (_f = result.content) != null ? _f : content;
705
+ typesPath = (_h = result.filePath) != null ? _h : typesPath;
706
+ content = (_i = result.content) != null ? _i : content;
660
707
  }
661
708
  }
662
709
  await import_fs_extra.default.writeFile(typesPath, content, "utf-8");
710
+ wroteFiles.add((0, import_vite2.normalizePath)(typesPath));
663
711
  }
664
712
  bundleDebug("insert index");
665
713
  if (rollupTypes) {
package/dist/index.mjs CHANGED
@@ -235,9 +235,11 @@ function transferSetupPosition(content) {
235
235
  // src/compile.ts
236
236
  var exportDefaultRE = /export\s+default/;
237
237
  var exportDefaultClassRE = /(?:(?:^|\n|;)\s*)export\s+default\s+class\s+([\w$]+)/;
238
+ var noScriptContent = "import { defineComponent } from 'vue'\nexport default defineComponent({})";
238
239
  var index = 1;
239
240
  var compileRoot = null;
240
241
  var compiler;
242
+ var vue;
241
243
  function requireCompiler() {
242
244
  if (!compiler) {
243
245
  if (compileRoot) {
@@ -260,15 +262,43 @@ function requireCompiler() {
260
262
  }
261
263
  return compiler;
262
264
  }
265
+ function isVue3() {
266
+ if (!vue) {
267
+ if (compileRoot) {
268
+ try {
269
+ vue = __require(__require.resolve("vue", { paths: [compileRoot] }));
270
+ } catch (e) {
271
+ }
272
+ }
273
+ if (!vue) {
274
+ try {
275
+ vue = __require("vue");
276
+ } catch (e) {
277
+ throw new Error("vue is not present in the dependency tree.\n");
278
+ }
279
+ }
280
+ }
281
+ return vue.version.startsWith("3");
282
+ }
263
283
  function setCompileRoot(root) {
264
284
  if (root && root !== compileRoot) {
265
285
  compileRoot = root;
266
286
  compiler = null;
267
287
  }
268
288
  }
289
+ function parseCode(code) {
290
+ const { parse } = requireCompiler();
291
+ let descriptor;
292
+ if (isVue3()) {
293
+ descriptor = parse(code).descriptor;
294
+ } else {
295
+ descriptor = parse({ source: code });
296
+ }
297
+ return descriptor;
298
+ }
269
299
  function compileVueCode(code) {
270
- const { parse, compileScript, rewriteDefault } = requireCompiler();
271
- const { descriptor } = parse(code);
300
+ const { compileScript, rewriteDefault } = requireCompiler();
301
+ const descriptor = parseCode(code);
272
302
  const { script, scriptSetup } = descriptor;
273
303
  let content = null;
274
304
  let ext = null;
@@ -296,6 +326,9 @@ const _sfc_main = ${classMatch[1]}`;
296
326
  content += "\nexport default _sfc_main\n";
297
327
  ext = script.lang || "js";
298
328
  }
329
+ } else {
330
+ content = noScriptContent;
331
+ ext = "ts";
299
332
  }
300
333
  return { content, ext };
301
334
  }
@@ -420,6 +453,7 @@ function dtsPlugin(options = {}) {
420
453
  const compilerOptions = (_a = options.compilerOptions) != null ? _a : {};
421
454
  let root;
422
455
  let entryRoot = (_b = options.entryRoot) != null ? _b : "";
456
+ let libName;
423
457
  let indexName;
424
458
  let aliases;
425
459
  let entries;
@@ -463,9 +497,11 @@ function dtsPlugin(options = {}) {
463
497
  logger.warn(chalk.yellow(`
464
498
  ${chalk.cyan("[vite:dts]")} You building not a library that may not need to generate declaration files.
465
499
  `));
500
+ libName = "_default";
466
501
  indexName = defaultIndex;
467
502
  } else {
468
503
  const filename = (_a2 = config.build.lib.fileName) != null ? _a2 : defaultIndex;
504
+ libName = config.build.lib.name || "_default";
469
505
  indexName = typeof filename === "string" ? filename : filename("es");
470
506
  if (!dtsRE2.test(indexName)) {
471
507
  indexName = `${tjsRE.test(indexName) ? indexName.replace(tjsRE, "") : indexName}.d.ts`;
@@ -528,7 +564,7 @@ ${chalk.cyan("[vite:dts]")} Can not resolve declaration directory, please check
528
564
  }
529
565
  },
530
566
  async closeBundle() {
531
- var _a2, _b2, _c, _d, _e, _f;
567
+ var _a2, _b2, _c, _d, _e, _f, _g, _h, _i;
532
568
  if (!outputDirs || !project || isBundle)
533
569
  return;
534
570
  logger.info(chalk.green(`
@@ -538,15 +574,17 @@ ${logPrefix} Start generate declaration files...`));
538
574
  sourceDtsFiles.clear();
539
575
  const startTime = Date.now();
540
576
  const tsConfig = (_a2 = readConfigFile(tsConfigPath, project.getFileSystem().readFileSync).config) != null ? _a2 : {};
541
- const include = (_c = (_b2 = options.include) != null ? _b2 : tsConfig.include) != null ? _c : "**/*";
542
- const exclude = (_d = options.exclude) != null ? _d : tsConfig.exclude;
577
+ const parentTsConfigPath = tsConfig.extends && ensureAbsolute(tsConfig.extends, root);
578
+ const parentTsConfig = parentTsConfigPath ? readConfigFile(parentTsConfigPath, project.getFileSystem().readFileSync).config : {};
579
+ const include = (_d = (_c = (_b2 = options.include) != null ? _b2 : tsConfig.include) != null ? _c : parentTsConfig.include) != null ? _d : "**/*";
580
+ const exclude = (_g = (_f = (_e = options.exclude) != null ? _e : tsConfig.exclude) != null ? _f : parentTsConfig.exclude) != null ? _g : "node_modules/**";
543
581
  bundleDebug("read config");
544
582
  const includedFileSet = /* @__PURE__ */ new Set();
545
583
  if (include && include.length) {
546
584
  const files = await glob(ensureArray(include).map(normalizeGlob), {
547
585
  cwd: root,
548
586
  absolute: true,
549
- ignore: ensureArray(exclude != null ? exclude : ["node_modules/**"]).map(normalizeGlob)
587
+ ignore: ensureArray(exclude).map(normalizeGlob)
550
588
  });
551
589
  files.forEach((file) => {
552
590
  if (dtsRE2.test(file)) {
@@ -629,19 +667,29 @@ ${logPrefix} Start generate declaration files...`));
629
667
  let typesPath = types ? resolve3(root, types) : resolve3(outputDir, indexName);
630
668
  if (!fs.existsSync(typesPath)) {
631
669
  const entry = entries[0];
632
- let filePath = normalizePath2(relative2(dirname3(typesPath), resolve3(outputDir, relative2(entryRoot, entry))));
633
- filePath = filePath.replace(tsRE, "");
670
+ const outputIndex = resolve3(outputDir, relative2(entryRoot, entry.replace(tsRE, ".d.ts")));
671
+ let filePath = normalizePath2(relative2(dirname3(typesPath), outputIndex));
672
+ filePath = filePath.replace(dtsRE2, "");
634
673
  filePath = fullRelativeRE.test(filePath) ? filePath : `./${filePath}`;
635
674
  let content = `export * from '${filePath}'
636
675
  `;
676
+ if (fs.existsSync(outputIndex)) {
677
+ const entryCodes = await fs.readFile(outputIndex, "utf-8");
678
+ if (entryCodes.includes("export default")) {
679
+ content += `import ${libName} from '${filePath}'
680
+ export default ${libName}
681
+ `;
682
+ }
683
+ }
637
684
  if (typeof beforeWriteFile === "function") {
638
685
  const result = beforeWriteFile(typesPath, content);
639
686
  if (result && isNativeObj(result)) {
640
- typesPath = (_e = result.filePath) != null ? _e : typesPath;
641
- content = (_f = result.content) != null ? _f : content;
687
+ typesPath = (_h = result.filePath) != null ? _h : typesPath;
688
+ content = (_i = result.content) != null ? _i : content;
642
689
  }
643
690
  }
644
691
  await fs.writeFile(typesPath, content, "utf-8");
692
+ wroteFiles.add(normalizePath2(typesPath));
645
693
  }
646
694
  bundleDebug("insert index");
647
695
  if (rollupTypes) {
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.3.0"
96
+ "version": "1.4.1"
97
97
  }