vite-plugin-dts 0.5.3 → 0.8.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
@@ -1,102 +1,119 @@
1
- # vite-plugin-dts
2
-
3
- **English** | [中文](./README.zh-CN.md)
4
-
5
- A vite plugin that generate `.d.ts` files from `.ts` or `.vue` source files for lib.
6
-
7
- ## Install
8
-
9
- ```sh
10
- yarn add vite-plugin-dts -D
11
- ```
12
-
13
- ## Usage
14
-
15
- ```ts
16
- import { resolve } from 'path'
17
- import { defineConfig } from 'vite'
18
- import dts from 'vite-plugin-dts'
19
-
20
- export default defineConfig({
21
- build: {
22
- lib: {
23
- entry: resolve(__dirname, 'src/index.ts'),
24
- name: 'MyLib',
25
- formats: ['es'],
26
- fileName: 'my-lib'
27
- }
28
- },
29
- plugins: [dts()]
30
- })
31
- ```
32
-
33
- ## Options
34
-
35
- ```ts
36
- import type { ts } from 'ts-morph'
37
-
38
- interface TransformWriteFile {
39
- filePath?: string
40
- content?: string
41
- }
42
-
43
- export interface PluginOptions {
44
- // Depends on the root directory
45
- // Defaults base on your vite config root options
46
- root?: string
47
-
48
- // Declaration files output directory
49
- // Defaults base on your vite config output options
50
- outputDir?: string
51
-
52
- // Project init compilerOptions using by ts-morph
53
- // Default: null
54
- compilerOptions?: ts.CompilerOptions | null
55
-
56
- // Project init tsconfig.json file path by ts-morph
57
- // Plugin also resolve incldue and exclude files from tsconfig.json
58
- // Default: 'tsconfig.json'
59
- tsConfigFilePath?: string
60
-
61
- // Whether transform file name '.vue.d.ts' to '.d.ts'
62
- // Default: false
63
- cleanVueFileName?: boolean
64
-
65
- // Whether transform dynamic import to static
66
- // eg. 'import('vue').DefineComponent' to 'import { DefineComponent } from "vue"'
67
- // Default: false
68
- staticImport?: boolean
69
-
70
- // Manual set include glob
71
- // Defaults base on your tsconfig.json include option
72
- include?: string | string[]
73
-
74
- // Manual set exclude glob
75
- // Defaults base on your tsconfig.json exclude option, be 'node_module/**' when empty
76
- exclude?: string | string[]
77
-
78
- // Whether generate types entry file
79
- // When true will from package.json types field if exists or `${outputDir}/index.d.ts`
80
- // Default: false
81
- insertTypesEntry?: boolean
82
-
83
- // Before declaration file be writed hook
84
- // You can transform declaration file-path and content through it
85
- // Default: () => {}
86
- beforeWriteFile?: (filePath: string, content: string) => void | TransformWriteFile
87
- }
88
- ```
89
-
90
- ## Example
91
-
92
- Clone and run the following script:
93
-
94
- ```sh
95
- yarn run test:e2e
96
- ```
97
-
98
- Then check `example/types`.
99
-
100
- ## License
101
-
102
- MIT License.
1
+ # vite-plugin-dts
2
+
3
+ **English** | [中文](./README.zh-CN.md)
4
+
5
+ A vite plugin that generate `.d.ts` files from `.ts` or `.vue` source files for lib.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ yarn add vite-plugin-dts -D
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { resolve } from 'path'
17
+ import { defineConfig } from 'vite'
18
+ import dts from 'vite-plugin-dts'
19
+
20
+ export default defineConfig({
21
+ build: {
22
+ lib: {
23
+ entry: resolve(__dirname, 'src/index.ts'),
24
+ name: 'MyLib',
25
+ formats: ['es'],
26
+ fileName: 'my-lib'
27
+ }
28
+ },
29
+ plugins: [dts()]
30
+ })
31
+ ```
32
+
33
+ ## Options
34
+
35
+ ```ts
36
+ import type { ts, Diagnostic } from 'ts-morph'
37
+
38
+ interface TransformWriteFile {
39
+ filePath?: string
40
+ content?: string
41
+ }
42
+
43
+ export interface PluginOptions {
44
+ // Depends on the root directory
45
+ // Defaults base on your vite config root options
46
+ root?: string
47
+
48
+ // Declaration files output directory
49
+ // Defaults base on your vite config output options
50
+ outputDir?: string
51
+
52
+ // Project init compilerOptions using by ts-morph
53
+ // Default: null
54
+ compilerOptions?: ts.CompilerOptions | null
55
+
56
+ // Project init tsconfig.json file path by ts-morph
57
+ // Plugin also resolve incldue and exclude files from tsconfig.json
58
+ // Default: 'tsconfig.json'
59
+ tsConfigFilePath?: string
60
+
61
+ // Whether transform file name '.vue.d.ts' to '.d.ts'
62
+ // Default: false
63
+ cleanVueFileName?: boolean
64
+
65
+ // Whether transform dynamic import to static
66
+ // eg. 'import('vue').DefineComponent' to 'import { DefineComponent } from "vue"'
67
+ // Default: false
68
+ staticImport?: boolean
69
+
70
+ // Manual set include glob
71
+ // Defaults base on your tsconfig.json include option
72
+ include?: string | string[]
73
+
74
+ // Manual set exclude glob
75
+ // Defaults base on your tsconfig.json exclude option, be 'node_module/**' when empty
76
+ exclude?: string | string[]
77
+
78
+ // Whether generate types entry file
79
+ // When true will from package.json types field if exists or `${outputDir}/index.d.ts`
80
+ // Default: false
81
+ insertTypesEntry?: boolean
82
+
83
+ // Whether copy .d.ts source files into outputDir
84
+ // Default: true
85
+ copyDtsFiles?: boolean
86
+
87
+ // Whether emit nothing when has any diagnostic
88
+ // Default: false
89
+ noEmitOnError?: boolean
90
+
91
+ // Whether log diagnostic informations
92
+ // Default: false
93
+ logDiagnostics?: boolean
94
+
95
+ // After emit diagnostic hook
96
+ // According to the length to judge whether there is any type error
97
+ // Default: () => {}
98
+ afterDiagnostic?: (diagnostics: Diagnostic[]) => void
99
+
100
+ // Before declaration file be writed hook
101
+ // You can transform declaration file-path and content through it
102
+ // Default: () => {}
103
+ beforeWriteFile?: (filePath: string, content: string) => void | TransformWriteFile
104
+ }
105
+ ```
106
+
107
+ ## Example
108
+
109
+ Clone and run the following script:
110
+
111
+ ```sh
112
+ yarn run test:e2e
113
+ ```
114
+
115
+ Then check `example/types`.
116
+
117
+ ## License
118
+
119
+ MIT License.
package/README.zh-CN.md CHANGED
@@ -1,102 +1,119 @@
1
- # vite-plugin-dts
2
-
3
- **中文** | [English](./README.md)
4
-
5
- 一款用于从 `.ts` 或 `.vue` 源文件生成 `.d.ts` 文件的 Vite 插件。
6
-
7
- ## 安装
8
-
9
- ```sh
10
- yarn add vite-plugin-dts -D
11
- ```
12
-
13
- ## 使用
14
-
15
- ```ts
16
- import { resolve } from 'path'
17
- import { defineConfig } from 'vite'
18
- import dts from 'vite-plugin-dts'
19
-
20
- export default defineConfig({
21
- build: {
22
- lib: {
23
- entry: resolve(__dirname, 'src/index.ts'),
24
- name: 'MyLib',
25
- formats: ['es'],
26
- fileName: 'my-lib'
27
- }
28
- },
29
- plugins: [dts()]
30
- })
31
- ```
32
-
33
- ## 选项
34
-
35
- ```ts
36
- import type { ts } from 'ts-morph'
37
-
38
- interface TransformWriteFile {
39
- filePath?: string
40
- content?: string
41
- }
42
-
43
- export interface PluginOptions {
44
- // 执行的根目录
45
- // 默认基于 vite 配置的 root 选项
46
- root?: string
47
-
48
- // 声明文件的输出目录
49
- // 默认基于 vite 配置的输出目录
50
- outputDir?: string
51
-
52
- // 提供给 ts-morph Project 初始化的 compilerOptions 选项
53
- // 默认值: null
54
- compilerOptions?: ts.CompilerOptions | null
55
-
56
- // 提供给 ts-morph Project 初始化的 tsconfig.json 路径
57
- // 插件也会读取 tsconfig.json 的 incldue 和 exclude 选项来解析文件
58
- // 默认值: 'tsconfig.json'
59
- tsConfigFilePath?: string
60
-
61
- // 是否将 '.vue.d.ts' 文件名转换为 '.d.ts'
62
- // 默认值: false
63
- cleanVueFileName?: boolean
64
-
65
- //是否将动态引入转换为静态
66
- // eg. 'import('vue').DefineComponent' 转换为 'import { DefineComponent } from "vue"'
67
- // 默认值: false
68
- staticImport?: boolean
69
-
70
- // 手动设置包含路径的 glob
71
- // 默认基于 tsconfig.json 的 include 选项
72
- include?: string | string[]
73
-
74
- // 手动设置排除路径的 glob
75
- // 默认基于 tsconfig.json 的 exclude 选线,未设置时为 'node_module/**'
76
- exclude?: string | string[]
77
-
78
- // 生否生成类型声明入口
79
- // 当为 true 时会基于 package.json 的 tpyes 字段生成,或者 `${outputDir}/index.d.ts`
80
- // 默认值: false
81
- insertTypesEntry?: boolean
82
-
83
- // 类型声明文件被写入前的钩子
84
- // 可以在钩子里转换文件路径和文件内容
85
- // 默认值: () => {}
86
- beforeWriteFile?: (filePath: string, content: string) => void | TransformWriteFile
87
- }
88
- ```
89
-
90
- ## Example
91
-
92
- 克隆项目然后执行下列命令:
93
-
94
- ```sh
95
- yarn run test:e2e
96
- ```
97
-
98
- 然后检查 `example/types` 目录。
99
-
100
- ## 授权
101
-
102
- MIT License
1
+ # vite-plugin-dts
2
+
3
+ **中文** | [English](./README.md)
4
+
5
+ 一款用于从 `.ts` 或 `.vue` 源文件生成 `.d.ts` 文件的 Vite 插件。
6
+
7
+ ## 安装
8
+
9
+ ```sh
10
+ yarn add vite-plugin-dts -D
11
+ ```
12
+
13
+ ## 使用
14
+
15
+ ```ts
16
+ import { resolve } from 'path'
17
+ import { defineConfig } from 'vite'
18
+ import dts from 'vite-plugin-dts'
19
+
20
+ export default defineConfig({
21
+ build: {
22
+ lib: {
23
+ entry: resolve(__dirname, 'src/index.ts'),
24
+ name: 'MyLib',
25
+ formats: ['es'],
26
+ fileName: 'my-lib'
27
+ }
28
+ },
29
+ plugins: [dts()]
30
+ })
31
+ ```
32
+
33
+ ## 选项
34
+
35
+ ```ts
36
+ import type { ts, Diagnostic } from 'ts-morph'
37
+
38
+ interface TransformWriteFile {
39
+ filePath?: string
40
+ content?: string
41
+ }
42
+
43
+ export interface PluginOptions {
44
+ // 执行的根目录
45
+ // 默认基于 vite 配置的 root 选项
46
+ root?: string
47
+
48
+ // 声明文件的输出目录
49
+ // 默认基于 vite 配置的输出目录
50
+ outputDir?: string
51
+
52
+ // 提供给 ts-morph Project 初始化的 compilerOptions 选项
53
+ // 默认值: null
54
+ compilerOptions?: ts.CompilerOptions | null
55
+
56
+ // 提供给 ts-morph Project 初始化的 tsconfig.json 路径
57
+ // 插件也会读取 tsconfig.json 的 incldue 和 exclude 选项来解析文件
58
+ // 默认值: 'tsconfig.json'
59
+ tsConfigFilePath?: string
60
+
61
+ // 是否将 '.vue.d.ts' 文件名转换为 '.d.ts'
62
+ // 默认值: false
63
+ cleanVueFileName?: boolean
64
+
65
+ //是否将动态引入转换为静态
66
+ // eg. 'import('vue').DefineComponent' 转换为 'import { DefineComponent } from "vue"'
67
+ // 默认值: false
68
+ staticImport?: boolean
69
+
70
+ // 手动设置包含路径的 glob
71
+ // 默认基于 tsconfig.json 的 include 选项
72
+ include?: string | string[]
73
+
74
+ // 手动设置排除路径的 glob
75
+ // 默认基于 tsconfig.json 的 exclude 选线,未设置时为 'node_module/**'
76
+ exclude?: string | string[]
77
+
78
+ // 是否生成类型声明入口
79
+ // 当为 true 时会基于 package.json 的 tpyes 字段生成,或者 `${outputDir}/index.d.ts`
80
+ // 默认值: false
81
+ insertTypesEntry?: boolean
82
+
83
+ // 是否将源码里的 .d.ts 文件复制到 outputDir
84
+ // 默认值: true
85
+ copyDtsFiles?: boolean
86
+
87
+ // 出现类型诊断信息时不生成类型文件
88
+ // 默认值: false
89
+ noEmitOnError?: boolean
90
+
91
+ // 是否打印类型诊断信息
92
+ // 默认值: false
93
+ logDiagnostics?: boolean
94
+
95
+ // 获取诊断信息后的钩子
96
+ // 可以根据参数 length 来判断有误类型错误
97
+ // 默认值: () => {}
98
+ afterDiagnostic?: (diagnostics: Diagnostic[]) => void
99
+
100
+ // 类型声明文件被写入前的钩子
101
+ // 可以在钩子里转换文件路径和文件内容
102
+ // 默认值: () => {}
103
+ beforeWriteFile?: (filePath: string, content: string) => void | TransformWriteFile
104
+ }
105
+ ```
106
+
107
+ ## Example
108
+
109
+ 克隆项目然后执行下列命令:
110
+
111
+ ```sh
112
+ yarn run test:e2e
113
+ ```
114
+
115
+ 然后检查 `example/types` 目录。
116
+
117
+ ## 授权
118
+
119
+ MIT License
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Plugin } from 'vite';
2
- import { ts } from 'ts-morph';
2
+ import { ts, Diagnostic } from 'ts-morph';
3
3
 
4
4
  interface TransformWriteFile {
5
5
  filePath?: string;
@@ -16,9 +16,12 @@ interface PluginOptions {
16
16
  staticImport?: boolean;
17
17
  clearPureImport?: boolean;
18
18
  insertTypesEntry?: boolean;
19
+ copyDtsFiles?: boolean;
20
+ noEmitOnError?: boolean;
21
+ logDiagnostics?: boolean;
22
+ afterDiagnostic?: (diagnostics: Diagnostic[]) => void;
19
23
  beforeWriteFile?: (filePath: string, content: string) => void | TransformWriteFile;
20
24
  }
21
- declare const _default: (options?: PluginOptions) => Plugin;
25
+ declare function dtsPlugin(options?: PluginOptions): Plugin;
22
26
 
23
- export default _default;
24
- export { PluginOptions };
27
+ export { PluginOptions, dtsPlugin as default };
package/dist/index.js CHANGED
@@ -1258,30 +1258,30 @@ var require_util = __commonJS({
1258
1258
  "node_modules/chalk/source/util.js"(exports, module) {
1259
1259
  "use strict";
1260
1260
  var stringReplaceAll = (string, substring, replacer) => {
1261
- let index = string.indexOf(substring);
1262
- if (index === -1) {
1261
+ let index2 = string.indexOf(substring);
1262
+ if (index2 === -1) {
1263
1263
  return string;
1264
1264
  }
1265
1265
  const substringLength = substring.length;
1266
1266
  let endIndex = 0;
1267
1267
  let returnValue = "";
1268
1268
  do {
1269
- returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
1270
- endIndex = index + substringLength;
1271
- index = string.indexOf(substring, endIndex);
1272
- } while (index !== -1);
1269
+ returnValue += string.substr(endIndex, index2 - endIndex) + substring + replacer;
1270
+ endIndex = index2 + substringLength;
1271
+ index2 = string.indexOf(substring, endIndex);
1272
+ } while (index2 !== -1);
1273
1273
  returnValue += string.substr(endIndex);
1274
1274
  return returnValue;
1275
1275
  };
1276
- var stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
1276
+ var stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index2) => {
1277
1277
  let endIndex = 0;
1278
1278
  let returnValue = "";
1279
1279
  do {
1280
- const gotCR = string[index - 1] === "\r";
1281
- returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
1282
- endIndex = index + 1;
1283
- index = string.indexOf("\n", endIndex);
1284
- } while (index !== -1);
1280
+ const gotCR = string[index2 - 1] === "\r";
1281
+ returnValue += string.substr(endIndex, (gotCR ? index2 - 1 : index2) - endIndex) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
1282
+ endIndex = index2 + 1;
1283
+ index2 = string.indexOf("\n", endIndex);
1284
+ } while (index2 !== -1);
1285
1285
  returnValue += string.substr(endIndex);
1286
1286
  return returnValue;
1287
1287
  };
@@ -1658,19 +1658,23 @@ async function runParallel(maxConcurrency, source, iteratorFn) {
1658
1658
  }
1659
1659
 
1660
1660
  // src/transform.ts
1661
+ var globSuffixRE = /^((?:.*\.[^.]+)|(?:\*+))$/;
1661
1662
  function normalizeGlob(path) {
1662
1663
  if (/[\\/]$/.test(path)) {
1663
1664
  return path + "**";
1664
- } else if (!/^((?:.*\.[^.]+)|(?:\*+))$/.test(path.split(/[\\/]/).pop())) {
1665
+ } else if (!globSuffixRE.test(path.split(/[\\/]/).pop())) {
1665
1666
  return path + "/**";
1666
1667
  }
1667
1668
  return path;
1668
1669
  }
1670
+ var globalDynamicTypeRE = /import\(['"][^;\n]+?['"]\)\.\w+[.()[\]<>,;\n\s]/g;
1671
+ var dynamicTypeRE = /import\(['"](.+)['"]\)\.(.+)([.()[\]<>,;\n\s])/;
1672
+ var importTypesRE = /import\s?(?:type)?\s?\{(.+)\}\s?from\s?['"].+['"]/;
1669
1673
  function transformDynamicImport(content) {
1670
1674
  const importMap = new Map();
1671
- content = content.replace(/import\(['"][^;\n]+?['"]\)\.\w+[.()[\]<>,;\n\s]/g, (str) => {
1675
+ content = content.replace(globalDynamicTypeRE, (str) => {
1672
1676
  var _a;
1673
- const matchResult = str.match(/import\(['"](.+)['"]\)\.(.+)([.()[\]<>,;\n\s])/);
1677
+ const matchResult = str.match(dynamicTypeRE);
1674
1678
  const libName = matchResult[1];
1675
1679
  const importSet = (_a = importMap.get(libName)) != null ? _a : importMap.set(libName, new Set()).get(libName);
1676
1680
  const usedType = matchResult[2];
@@ -1681,7 +1685,7 @@ function transformDynamicImport(content) {
1681
1685
  const importReg = new RegExp(`import\\s?(?:type)?\\s?\\{[^;\\n]+\\}\\s?from\\s?['"]${libName}['"]`, "g");
1682
1686
  const matchResult = content.match(importReg);
1683
1687
  if (matchResult == null ? void 0 : matchResult[0]) {
1684
- const importedTypes = matchResult[0].match(/import\s?(?:type)?\s?\{(.+)\}\s?from\s?['"].+['"]/)[1].trim().split(",");
1688
+ const importedTypes = matchResult[0].match(importTypesRE)[1].trim().split(",");
1685
1689
  content = content.replace(matchResult[0], `import type { ${Array.from(importSet).concat(importedTypes).join(", ")} } from '${libName}'`);
1686
1690
  } else {
1687
1691
  content = `import type { ${Array.from(importSet).join(", ")} } from '${libName}';
@@ -1699,40 +1703,115 @@ function isAliasMatch(alias, importee) {
1699
1703
  return true;
1700
1704
  return importee.indexOf(alias.find) === 0 && importee.substring(alias.find.length)[0] === "/";
1701
1705
  }
1706
+ var globalImportRE = /(?:(?:import|export)\s?(?:type)?\s?(?:(?:\{[^;\n]+\})|(?:[^;\n]+))\s?from\s?['"][^;\n]+['"])|(?:import\(['"][^;\n]+?['"]\))/g;
1707
+ var staticImportRE = /(?:import|export)\s?(?:type)?\s?\{?.+\}?\s?from\s?['"](.+)['"]/;
1708
+ var dynamicImportRE = /import\(['"]([^;\n]+?)['"]\)/;
1709
+ var simpleStaticImportRE = /((?:import|export).+from\s?)['"](.+)['"]/;
1710
+ var simpleDynamicImportRE = /(import\()['"](.+)['"]\)/;
1702
1711
  function transformAliasImport(filePath, content, aliases) {
1703
1712
  if (!aliases.length)
1704
1713
  return content;
1705
- return content.replace(/(?:(?:import|export)\s?(?:type)?\s?\{[^;\n]+\}\s?from\s?['"][^;\n]+['"])|(?:import\(['"][^;\n]+?['"]\))/g, (str) => {
1706
- let matchResult = str.match(/(?:import|export)\s?(?:type)?\s?\{.+\}\s?from\s?['"](.+)['"]/);
1714
+ return content.replace(globalImportRE, (str) => {
1715
+ let matchResult = str.match(staticImportRE);
1707
1716
  let isDynamic = false;
1708
1717
  if (!matchResult) {
1709
- matchResult = str.match(/import\(['"]([^;\n]+?)['"]\)/);
1718
+ matchResult = str.match(dynamicImportRE);
1710
1719
  isDynamic = true;
1711
1720
  }
1712
1721
  if (matchResult == null ? void 0 : matchResult[1]) {
1713
1722
  const matchedAlias = aliases.find((alias) => isAliasMatch(alias, matchResult[1]));
1714
1723
  if (matchedAlias) {
1715
- return str.replace(isDynamic ? /(import\()['"](.+)['"]\)/ : /((?:import|export).+from\s?)['"](.+)['"]/, `$1'${matchResult[1].replace(matchedAlias.find, _path.isAbsolute.call(void 0, matchedAlias.replacement) ? _vite.normalizePath.call(void 0, _path.relative.call(void 0, _path.dirname.call(void 0, filePath), matchedAlias.replacement)) : _vite.normalizePath.call(void 0, matchedAlias.replacement))}'${isDynamic ? ")" : ""}`);
1724
+ const truthPath = _path.isAbsolute.call(void 0, matchedAlias.replacement) ? _vite.normalizePath.call(void 0, _path.relative.call(void 0, _path.dirname.call(void 0, filePath), matchedAlias.replacement)) : _vite.normalizePath.call(void 0, matchedAlias.replacement);
1725
+ return str.replace(isDynamic ? simpleDynamicImportRE : simpleStaticImportRE, `$1'${matchResult[1].replace(matchedAlias.find, truthPath.startsWith(".") ? truthPath : `./${truthPath}`)}'${isDynamic ? ")" : ""}`);
1716
1726
  }
1717
1727
  }
1718
1728
  return str;
1719
1729
  });
1720
1730
  }
1731
+ var pureImportRE = /import\s?['"][^;\n]+?['"];?\n?/g;
1721
1732
  function removePureImport(content) {
1722
- return content.replace(/import\s?['"][^;\n]+?['"];?\n?/g, "");
1733
+ return content.replace(pureImportRE, "");
1734
+ }
1735
+ var setupFunctionRE = /function setup\([\s\S]+\)\s+?\{[\s\S]+return __returned__\n\}/;
1736
+ function transferSetupPosition(content) {
1737
+ const match = content.match(setupFunctionRE);
1738
+ if (match) {
1739
+ const setupFunction = match[0];
1740
+ return content.replace(setupFunction, "").replace("setup})", setupFunction.slice("function ".length) + "\n\r})");
1741
+ }
1742
+ return content;
1743
+ }
1744
+
1745
+ // src/compile.ts
1746
+ var exportDefaultClassRE = /(?:(?:^|\n|;)\s*)export\s+default\s+class\s+([\w$]+)/;
1747
+ var index = 1;
1748
+ var compiler;
1749
+ function requireCompiler() {
1750
+ if (!compiler) {
1751
+ try {
1752
+ compiler = __require("@vue/compiler-sfc");
1753
+ } catch (e) {
1754
+ throw new Error("@vue/compiler-sfc is not present in the dependency tree.\n");
1755
+ }
1756
+ }
1757
+ return compiler;
1758
+ }
1759
+ function compileVueCode(code) {
1760
+ const { parse, compileScript, rewriteDefault } = requireCompiler();
1761
+ const { descriptor } = parse(code);
1762
+ const { script, scriptSetup } = descriptor;
1763
+ let content = null;
1764
+ let isTs = false;
1765
+ let isJs = false;
1766
+ if (script || scriptSetup) {
1767
+ if (scriptSetup) {
1768
+ const compiled = compileScript(descriptor, {
1769
+ id: `${index++}`
1770
+ });
1771
+ const classMatch = compiled.content.match(exportDefaultClassRE);
1772
+ if (classMatch) {
1773
+ content = compiled.content.replace(exportDefaultClassRE, `
1774
+ class $1`) + `
1775
+ const _sfc_main = ${classMatch[1]}`;
1776
+ if (/export\s+default/.test(content)) {
1777
+ content = rewriteDefault(compiled.content, `_sfc_main`);
1778
+ }
1779
+ } else {
1780
+ content = rewriteDefault(compiled.content, `_sfc_main`);
1781
+ }
1782
+ content = transferSetupPosition(content);
1783
+ content += "\nexport default _sfc_main\n";
1784
+ if (scriptSetup.lang === "ts") {
1785
+ isTs = true;
1786
+ } else if (!scriptSetup.lang || scriptSetup.lang === "js") {
1787
+ isJs = true;
1788
+ }
1789
+ } else if (script && script.content) {
1790
+ content = script.content;
1791
+ if (script.lang === "ts") {
1792
+ isTs = true;
1793
+ } else if (!script.lang || script.lang === "js") {
1794
+ isJs = true;
1795
+ }
1796
+ }
1797
+ }
1798
+ return { content, isTs, isJs };
1723
1799
  }
1724
1800
 
1725
1801
  // src/index.ts
1726
1802
  var noneExport = "export {};\n";
1727
1803
  var noop = () => {
1728
1804
  };
1729
- var src_default = (options = {}) => {
1805
+ function dtsPlugin(options = {}) {
1730
1806
  const {
1731
1807
  tsConfigFilePath = "tsconfig.json",
1732
1808
  cleanVueFileName = false,
1733
1809
  staticImport = false,
1734
1810
  clearPureImport = true,
1735
1811
  insertTypesEntry = false,
1812
+ noEmitOnError = false,
1813
+ logDiagnostics = false,
1814
+ afterDiagnostic = noop,
1736
1815
  beforeWriteFile = noop
1737
1816
  } = options;
1738
1817
  const compilerOptions = options.compilerOptions || {};
@@ -1744,7 +1823,9 @@ var src_default = (options = {}) => {
1744
1823
  let tsConfigPath;
1745
1824
  let outputDir;
1746
1825
  let isBundle = false;
1747
- const sourceFiles = [];
1826
+ const sourceDtsFiles = new Set();
1827
+ let hasJsVue = false;
1828
+ let allowJs = false;
1748
1829
  return {
1749
1830
  name: "vite:dts",
1750
1831
  apply: "build",
@@ -1762,109 +1843,106 @@ var src_default = (options = {}) => {
1762
1843
  }
1763
1844
  },
1764
1845
  configResolved(config) {
1846
+ var _a;
1765
1847
  if (isBundle)
1766
1848
  return;
1767
1849
  logger = config.logger;
1768
1850
  if (!config.build.lib) {
1769
- logger.warn(import_chalk.default.yellow("\n[vite:dts] You building not a library that may not need to generate declaration files.\n"));
1851
+ logger.warn(import_chalk.default.yellow(`
1852
+ ${import_chalk.default.cyan("[vite:dts]")} You building not a library that may not need to generate declaration files.
1853
+ `));
1770
1854
  }
1771
1855
  root = ensureAbsolute(options.root || "", config.root);
1772
1856
  tsConfigPath = ensureAbsolute(tsConfigFilePath, root);
1773
1857
  outputDir = options.outputDir ? ensureAbsolute(options.outputDir, root) : ensureAbsolute(config.build.outDir, root);
1774
1858
  if (!outputDir) {
1775
- logger.error(import_chalk.default.red("\n[vite:dts] Can not resolve declaration directory, please check your vite config and plugin options.\n"));
1859
+ logger.error(import_chalk.default.red(`
1860
+ ${import_chalk.default.cyan("[vite:dts]")} Can not resolve declaration directory, please check your vite config and plugin options.
1861
+ `));
1776
1862
  return;
1777
1863
  }
1778
1864
  compilerOptions.rootDir = compilerOptions.rootDir || root;
1779
1865
  project = new (0, _tsmorph.Project)({
1780
1866
  compilerOptions: mergeObjects(compilerOptions || {}, {
1867
+ noEmitOnError,
1781
1868
  outDir: ".",
1869
+ declarationDir: null,
1782
1870
  declaration: true,
1783
- emitDeclarationOnly: true,
1784
- noEmitOnError: true
1871
+ noEmit: false,
1872
+ emitDeclarationOnly: true
1785
1873
  }),
1786
1874
  tsConfigFilePath: tsConfigPath,
1787
1875
  skipAddingFilesFromTsConfig: true
1788
1876
  });
1877
+ allowJs = (_a = project.getCompilerOptions().allowJs) != null ? _a : false;
1789
1878
  },
1790
1879
  buildStart(inputOptions) {
1791
1880
  entries = Array.isArray(inputOptions.input) ? inputOptions.input : Object.values(inputOptions.input);
1792
1881
  },
1882
+ transform(code, id) {
1883
+ if (/\.vue$/.test(id)) {
1884
+ const { content, isTs, isJs } = compileVueCode(code);
1885
+ if (content) {
1886
+ if (isJs)
1887
+ hasJsVue = true;
1888
+ project.createSourceFile(id + (isTs ? ".ts" : ".js"), content, { overwrite: true });
1889
+ }
1890
+ } else if (!id.includes(".vue?vue") && (/\.tsx?$/.test(id) || allowJs && /\.jsx?$/.test(id))) {
1891
+ project.addSourceFileAtPath(id);
1892
+ }
1893
+ return null;
1894
+ },
1895
+ watchChange(id) {
1896
+ if (/\.(vue|(t|j)sx?)$/.test(id)) {
1897
+ isBundle = false;
1898
+ }
1899
+ },
1793
1900
  async closeBundle() {
1794
1901
  if (!outputDir || !project || isBundle)
1795
1902
  return;
1903
+ logger.info(import_chalk.default.green(`
1904
+ ${import_chalk.default.cyan("[vite:dts]")} Compiling source files...`));
1796
1905
  isBundle = true;
1797
- const allowJs = project.getCompilerOptions().allowJs;
1906
+ sourceDtsFiles.clear();
1798
1907
  const tsConfig = JSON.parse(await _fsextra2.default.readFile(tsConfigPath, "utf-8"));
1799
1908
  const include = options.include || tsConfig.include;
1800
1909
  const exclude = options.exclude || tsConfig.exclude;
1910
+ const includedFileSet = new Set();
1801
1911
  if (include && include.length) {
1802
1912
  const files = await _fastglob2.default.call(void 0, ensureArray(include).map(normalizeGlob), {
1803
1913
  cwd: root,
1804
1914
  absolute: true,
1805
1915
  ignore: ensureArray(exclude || ["node_modules/**"]).map(normalizeGlob)
1806
1916
  });
1807
- let index = 1;
1808
- let compiler;
1809
- const requireCompiler = () => {
1810
- if (!compiler) {
1811
- try {
1812
- compiler = __require("@vue/compiler-sfc");
1813
- } catch (e) {
1814
- throw new Error("@vue/compiler-sfc is not present in the dependency tree.\n");
1815
- }
1917
+ files.forEach((file) => {
1918
+ includedFileSet.add(/\.d\.tsx?$/.test(file) ? file : `${/\.(t|j)sx?$/.test(file) ? file.replace(/\.(t|j)sx?$/, "") : file}.d.ts`);
1919
+ if (/\.d\.tsx?$/.test(file)) {
1920
+ sourceDtsFiles.add(file);
1816
1921
  }
1817
- return compiler;
1818
- };
1819
- let hasJs = false;
1820
- await Promise.all(files.map(async (file) => {
1821
- if (/\.vue$/.test(file)) {
1822
- const { parse, compileScript } = requireCompiler();
1823
- const sfc = parse(await _fsextra2.default.readFile(file, "utf-8"));
1824
- const { script, scriptSetup } = sfc.descriptor;
1825
- if (script || scriptSetup) {
1826
- let content = "";
1827
- let isTs = false;
1828
- if (script && script.content) {
1829
- content += script.content;
1830
- if (script.lang === "ts") {
1831
- isTs = true;
1832
- } else if (!script.lang || script.lang === "js") {
1833
- hasJs = true;
1834
- }
1835
- }
1836
- if (scriptSetup) {
1837
- const compiled = compileScript(sfc.descriptor, {
1838
- id: `${index++}`
1839
- });
1840
- content += compiled.content;
1841
- if (scriptSetup.lang === "ts") {
1842
- isTs = true;
1843
- } else if (!scriptSetup.lang || scriptSetup.lang === "js") {
1844
- hasJs = true;
1845
- }
1846
- }
1847
- sourceFiles.push(project.createSourceFile(file + (isTs ? ".ts" : ".js"), content));
1848
- }
1849
- } else if (/\.tsx?$/.test(file) || allowJs && /\.jsx?$/.test(file)) {
1850
- sourceFiles.push(project.addSourceFileAtPath(file));
1851
- }
1852
- }));
1853
- if (hasJs) {
1922
+ });
1923
+ if (hasJsVue) {
1854
1924
  if (!allowJs) {
1855
- logger.warn(import_chalk.default.yellow("\n[vite:dts] Some js files are referenced, but you may not enable the 'allowJs' option.\n"));
1925
+ logger.warn(import_chalk.default.yellow(`${import_chalk.default.cyan("[vite:dts]")} Some js files are referenced, but you may not enable the 'allowJs' option.`));
1856
1926
  }
1857
1927
  project.compilerOptions.set({ allowJs: true });
1858
1928
  }
1859
1929
  }
1930
+ project.resolveSourceFileDependencies();
1860
1931
  const diagnostics = project.getPreEmitDiagnostics();
1861
- logger.warn(project.formatDiagnosticsWithColorAndContext(diagnostics));
1932
+ if ((diagnostics == null ? void 0 : diagnostics.length) && logDiagnostics) {
1933
+ logger.warn(project.formatDiagnosticsWithColorAndContext(diagnostics));
1934
+ }
1935
+ if (typeof afterDiagnostic === "function") {
1936
+ afterDiagnostic(diagnostics);
1937
+ }
1938
+ logger.info(import_chalk.default.green(`${import_chalk.default.cyan("[vite:dts]")} Generating declaration files...`));
1862
1939
  await runParallel(_os2.default.cpus().length, project.emitToMemory().getFiles(), async (outputFile) => {
1863
1940
  let filePath = outputFile.filePath;
1864
1941
  let content = outputFile.text;
1865
- if (clearPureImport && content === noneExport)
1942
+ const isMapFile = filePath.endsWith(".map");
1943
+ if (!includedFileSet.has(isMapFile ? filePath.slice(0, -4) : filePath) || clearPureImport && content === noneExport)
1866
1944
  return;
1867
- if (content !== noneExport) {
1945
+ if (!isMapFile && content !== noneExport) {
1868
1946
  content = clearPureImport ? removePureImport(content) : content;
1869
1947
  content = transformAliasImport(filePath, content, aliases);
1870
1948
  content = staticImport ? transformDynamicImport(content) : content;
@@ -1880,6 +1958,11 @@ var src_default = (options = {}) => {
1880
1958
  await _fsextra2.default.mkdir(_path.dirname.call(void 0, filePath), { recursive: true });
1881
1959
  await _fsextra2.default.writeFile(filePath, cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content, "utf8");
1882
1960
  });
1961
+ await Promise.all(Array.from(sourceDtsFiles).map(async (filePath) => {
1962
+ const targetPath = _path.resolve.call(void 0, outputDir, _path.relative.call(void 0, root, filePath));
1963
+ await _fsextra2.default.mkdir(_path.dirname.call(void 0, targetPath), { recursive: true });
1964
+ await _fsextra2.default.copyFile(filePath, targetPath);
1965
+ }));
1883
1966
  if (insertTypesEntry) {
1884
1967
  const pkgPath = _path.resolve.call(void 0, root, "package.json");
1885
1968
  const pkg = _fsextra2.default.existsSync(pkgPath) ? JSON.parse(await _fsextra2.default.readFile(pkgPath, "utf-8")) : {};
@@ -1894,9 +1977,11 @@ var src_default = (options = {}) => {
1894
1977
  await _fsextra2.default.writeFile(typesPath, content, "utf-8");
1895
1978
  }
1896
1979
  }
1980
+ logger.info(import_chalk.default.green(`${import_chalk.default.cyan("[vite:dts]")} Declaration files built.
1981
+ `));
1897
1982
  }
1898
1983
  };
1899
- };
1984
+ }
1900
1985
 
1901
1986
 
1902
- exports.default = src_default;
1987
+ exports.default = dtsPlugin;
package/dist/index.mjs CHANGED
@@ -1258,30 +1258,30 @@ var require_util = __commonJS({
1258
1258
  "node_modules/chalk/source/util.js"(exports, module) {
1259
1259
  "use strict";
1260
1260
  var stringReplaceAll = (string, substring, replacer) => {
1261
- let index = string.indexOf(substring);
1262
- if (index === -1) {
1261
+ let index2 = string.indexOf(substring);
1262
+ if (index2 === -1) {
1263
1263
  return string;
1264
1264
  }
1265
1265
  const substringLength = substring.length;
1266
1266
  let endIndex = 0;
1267
1267
  let returnValue = "";
1268
1268
  do {
1269
- returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
1270
- endIndex = index + substringLength;
1271
- index = string.indexOf(substring, endIndex);
1272
- } while (index !== -1);
1269
+ returnValue += string.substr(endIndex, index2 - endIndex) + substring + replacer;
1270
+ endIndex = index2 + substringLength;
1271
+ index2 = string.indexOf(substring, endIndex);
1272
+ } while (index2 !== -1);
1273
1273
  returnValue += string.substr(endIndex);
1274
1274
  return returnValue;
1275
1275
  };
1276
- var stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
1276
+ var stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index2) => {
1277
1277
  let endIndex = 0;
1278
1278
  let returnValue = "";
1279
1279
  do {
1280
- const gotCR = string[index - 1] === "\r";
1281
- returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
1282
- endIndex = index + 1;
1283
- index = string.indexOf("\n", endIndex);
1284
- } while (index !== -1);
1280
+ const gotCR = string[index2 - 1] === "\r";
1281
+ returnValue += string.substr(endIndex, (gotCR ? index2 - 1 : index2) - endIndex) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
1282
+ endIndex = index2 + 1;
1283
+ index2 = string.indexOf("\n", endIndex);
1284
+ } while (index2 !== -1);
1285
1285
  returnValue += string.substr(endIndex);
1286
1286
  return returnValue;
1287
1287
  };
@@ -1658,19 +1658,23 @@ async function runParallel(maxConcurrency, source, iteratorFn) {
1658
1658
  }
1659
1659
 
1660
1660
  // src/transform.ts
1661
+ var globSuffixRE = /^((?:.*\.[^.]+)|(?:\*+))$/;
1661
1662
  function normalizeGlob(path) {
1662
1663
  if (/[\\/]$/.test(path)) {
1663
1664
  return path + "**";
1664
- } else if (!/^((?:.*\.[^.]+)|(?:\*+))$/.test(path.split(/[\\/]/).pop())) {
1665
+ } else if (!globSuffixRE.test(path.split(/[\\/]/).pop())) {
1665
1666
  return path + "/**";
1666
1667
  }
1667
1668
  return path;
1668
1669
  }
1670
+ var globalDynamicTypeRE = /import\(['"][^;\n]+?['"]\)\.\w+[.()[\]<>,;\n\s]/g;
1671
+ var dynamicTypeRE = /import\(['"](.+)['"]\)\.(.+)([.()[\]<>,;\n\s])/;
1672
+ var importTypesRE = /import\s?(?:type)?\s?\{(.+)\}\s?from\s?['"].+['"]/;
1669
1673
  function transformDynamicImport(content) {
1670
1674
  const importMap = new Map();
1671
- content = content.replace(/import\(['"][^;\n]+?['"]\)\.\w+[.()[\]<>,;\n\s]/g, (str) => {
1675
+ content = content.replace(globalDynamicTypeRE, (str) => {
1672
1676
  var _a;
1673
- const matchResult = str.match(/import\(['"](.+)['"]\)\.(.+)([.()[\]<>,;\n\s])/);
1677
+ const matchResult = str.match(dynamicTypeRE);
1674
1678
  const libName = matchResult[1];
1675
1679
  const importSet = (_a = importMap.get(libName)) != null ? _a : importMap.set(libName, new Set()).get(libName);
1676
1680
  const usedType = matchResult[2];
@@ -1681,7 +1685,7 @@ function transformDynamicImport(content) {
1681
1685
  const importReg = new RegExp(`import\\s?(?:type)?\\s?\\{[^;\\n]+\\}\\s?from\\s?['"]${libName}['"]`, "g");
1682
1686
  const matchResult = content.match(importReg);
1683
1687
  if (matchResult == null ? void 0 : matchResult[0]) {
1684
- const importedTypes = matchResult[0].match(/import\s?(?:type)?\s?\{(.+)\}\s?from\s?['"].+['"]/)[1].trim().split(",");
1688
+ const importedTypes = matchResult[0].match(importTypesRE)[1].trim().split(",");
1685
1689
  content = content.replace(matchResult[0], `import type { ${Array.from(importSet).concat(importedTypes).join(", ")} } from '${libName}'`);
1686
1690
  } else {
1687
1691
  content = `import type { ${Array.from(importSet).join(", ")} } from '${libName}';
@@ -1699,40 +1703,115 @@ function isAliasMatch(alias, importee) {
1699
1703
  return true;
1700
1704
  return importee.indexOf(alias.find) === 0 && importee.substring(alias.find.length)[0] === "/";
1701
1705
  }
1706
+ var globalImportRE = /(?:(?:import|export)\s?(?:type)?\s?(?:(?:\{[^;\n]+\})|(?:[^;\n]+))\s?from\s?['"][^;\n]+['"])|(?:import\(['"][^;\n]+?['"]\))/g;
1707
+ var staticImportRE = /(?:import|export)\s?(?:type)?\s?\{?.+\}?\s?from\s?['"](.+)['"]/;
1708
+ var dynamicImportRE = /import\(['"]([^;\n]+?)['"]\)/;
1709
+ var simpleStaticImportRE = /((?:import|export).+from\s?)['"](.+)['"]/;
1710
+ var simpleDynamicImportRE = /(import\()['"](.+)['"]\)/;
1702
1711
  function transformAliasImport(filePath, content, aliases) {
1703
1712
  if (!aliases.length)
1704
1713
  return content;
1705
- return content.replace(/(?:(?:import|export)\s?(?:type)?\s?\{[^;\n]+\}\s?from\s?['"][^;\n]+['"])|(?:import\(['"][^;\n]+?['"]\))/g, (str) => {
1706
- let matchResult = str.match(/(?:import|export)\s?(?:type)?\s?\{.+\}\s?from\s?['"](.+)['"]/);
1714
+ return content.replace(globalImportRE, (str) => {
1715
+ let matchResult = str.match(staticImportRE);
1707
1716
  let isDynamic = false;
1708
1717
  if (!matchResult) {
1709
- matchResult = str.match(/import\(['"]([^;\n]+?)['"]\)/);
1718
+ matchResult = str.match(dynamicImportRE);
1710
1719
  isDynamic = true;
1711
1720
  }
1712
1721
  if (matchResult == null ? void 0 : matchResult[1]) {
1713
1722
  const matchedAlias = aliases.find((alias) => isAliasMatch(alias, matchResult[1]));
1714
1723
  if (matchedAlias) {
1715
- return str.replace(isDynamic ? /(import\()['"](.+)['"]\)/ : /((?:import|export).+from\s?)['"](.+)['"]/, `$1'${matchResult[1].replace(matchedAlias.find, isAbsolute2(matchedAlias.replacement) ? normalizePath(relative(dirname(filePath), matchedAlias.replacement)) : normalizePath(matchedAlias.replacement))}'${isDynamic ? ")" : ""}`);
1724
+ const truthPath = isAbsolute2(matchedAlias.replacement) ? normalizePath(relative(dirname(filePath), matchedAlias.replacement)) : normalizePath(matchedAlias.replacement);
1725
+ return str.replace(isDynamic ? simpleDynamicImportRE : simpleStaticImportRE, `$1'${matchResult[1].replace(matchedAlias.find, truthPath.startsWith(".") ? truthPath : `./${truthPath}`)}'${isDynamic ? ")" : ""}`);
1716
1726
  }
1717
1727
  }
1718
1728
  return str;
1719
1729
  });
1720
1730
  }
1731
+ var pureImportRE = /import\s?['"][^;\n]+?['"];?\n?/g;
1721
1732
  function removePureImport(content) {
1722
- return content.replace(/import\s?['"][^;\n]+?['"];?\n?/g, "");
1733
+ return content.replace(pureImportRE, "");
1734
+ }
1735
+ var setupFunctionRE = /function setup\([\s\S]+\)\s+?\{[\s\S]+return __returned__\n\}/;
1736
+ function transferSetupPosition(content) {
1737
+ const match = content.match(setupFunctionRE);
1738
+ if (match) {
1739
+ const setupFunction = match[0];
1740
+ return content.replace(setupFunction, "").replace("setup})", setupFunction.slice("function ".length) + "\n\r})");
1741
+ }
1742
+ return content;
1743
+ }
1744
+
1745
+ // src/compile.ts
1746
+ var exportDefaultClassRE = /(?:(?:^|\n|;)\s*)export\s+default\s+class\s+([\w$]+)/;
1747
+ var index = 1;
1748
+ var compiler;
1749
+ function requireCompiler() {
1750
+ if (!compiler) {
1751
+ try {
1752
+ compiler = __require("@vue/compiler-sfc");
1753
+ } catch (e) {
1754
+ throw new Error("@vue/compiler-sfc is not present in the dependency tree.\n");
1755
+ }
1756
+ }
1757
+ return compiler;
1758
+ }
1759
+ function compileVueCode(code) {
1760
+ const { parse, compileScript, rewriteDefault } = requireCompiler();
1761
+ const { descriptor } = parse(code);
1762
+ const { script, scriptSetup } = descriptor;
1763
+ let content = null;
1764
+ let isTs = false;
1765
+ let isJs = false;
1766
+ if (script || scriptSetup) {
1767
+ if (scriptSetup) {
1768
+ const compiled = compileScript(descriptor, {
1769
+ id: `${index++}`
1770
+ });
1771
+ const classMatch = compiled.content.match(exportDefaultClassRE);
1772
+ if (classMatch) {
1773
+ content = compiled.content.replace(exportDefaultClassRE, `
1774
+ class $1`) + `
1775
+ const _sfc_main = ${classMatch[1]}`;
1776
+ if (/export\s+default/.test(content)) {
1777
+ content = rewriteDefault(compiled.content, `_sfc_main`);
1778
+ }
1779
+ } else {
1780
+ content = rewriteDefault(compiled.content, `_sfc_main`);
1781
+ }
1782
+ content = transferSetupPosition(content);
1783
+ content += "\nexport default _sfc_main\n";
1784
+ if (scriptSetup.lang === "ts") {
1785
+ isTs = true;
1786
+ } else if (!scriptSetup.lang || scriptSetup.lang === "js") {
1787
+ isJs = true;
1788
+ }
1789
+ } else if (script && script.content) {
1790
+ content = script.content;
1791
+ if (script.lang === "ts") {
1792
+ isTs = true;
1793
+ } else if (!script.lang || script.lang === "js") {
1794
+ isJs = true;
1795
+ }
1796
+ }
1797
+ }
1798
+ return { content, isTs, isJs };
1723
1799
  }
1724
1800
 
1725
1801
  // src/index.ts
1726
1802
  var noneExport = "export {};\n";
1727
1803
  var noop = () => {
1728
1804
  };
1729
- var src_default = (options = {}) => {
1805
+ function dtsPlugin(options = {}) {
1730
1806
  const {
1731
1807
  tsConfigFilePath = "tsconfig.json",
1732
1808
  cleanVueFileName = false,
1733
1809
  staticImport = false,
1734
1810
  clearPureImport = true,
1735
1811
  insertTypesEntry = false,
1812
+ noEmitOnError = false,
1813
+ logDiagnostics = false,
1814
+ afterDiagnostic = noop,
1736
1815
  beforeWriteFile = noop
1737
1816
  } = options;
1738
1817
  const compilerOptions = options.compilerOptions || {};
@@ -1744,7 +1823,9 @@ var src_default = (options = {}) => {
1744
1823
  let tsConfigPath;
1745
1824
  let outputDir;
1746
1825
  let isBundle = false;
1747
- const sourceFiles = [];
1826
+ const sourceDtsFiles = new Set();
1827
+ let hasJsVue = false;
1828
+ let allowJs = false;
1748
1829
  return {
1749
1830
  name: "vite:dts",
1750
1831
  apply: "build",
@@ -1762,109 +1843,106 @@ var src_default = (options = {}) => {
1762
1843
  }
1763
1844
  },
1764
1845
  configResolved(config) {
1846
+ var _a;
1765
1847
  if (isBundle)
1766
1848
  return;
1767
1849
  logger = config.logger;
1768
1850
  if (!config.build.lib) {
1769
- logger.warn(import_chalk.default.yellow("\n[vite:dts] You building not a library that may not need to generate declaration files.\n"));
1851
+ logger.warn(import_chalk.default.yellow(`
1852
+ ${import_chalk.default.cyan("[vite:dts]")} You building not a library that may not need to generate declaration files.
1853
+ `));
1770
1854
  }
1771
1855
  root = ensureAbsolute(options.root || "", config.root);
1772
1856
  tsConfigPath = ensureAbsolute(tsConfigFilePath, root);
1773
1857
  outputDir = options.outputDir ? ensureAbsolute(options.outputDir, root) : ensureAbsolute(config.build.outDir, root);
1774
1858
  if (!outputDir) {
1775
- logger.error(import_chalk.default.red("\n[vite:dts] Can not resolve declaration directory, please check your vite config and plugin options.\n"));
1859
+ logger.error(import_chalk.default.red(`
1860
+ ${import_chalk.default.cyan("[vite:dts]")} Can not resolve declaration directory, please check your vite config and plugin options.
1861
+ `));
1776
1862
  return;
1777
1863
  }
1778
1864
  compilerOptions.rootDir = compilerOptions.rootDir || root;
1779
1865
  project = new Project({
1780
1866
  compilerOptions: mergeObjects(compilerOptions || {}, {
1867
+ noEmitOnError,
1781
1868
  outDir: ".",
1869
+ declarationDir: null,
1782
1870
  declaration: true,
1783
- emitDeclarationOnly: true,
1784
- noEmitOnError: true
1871
+ noEmit: false,
1872
+ emitDeclarationOnly: true
1785
1873
  }),
1786
1874
  tsConfigFilePath: tsConfigPath,
1787
1875
  skipAddingFilesFromTsConfig: true
1788
1876
  });
1877
+ allowJs = (_a = project.getCompilerOptions().allowJs) != null ? _a : false;
1789
1878
  },
1790
1879
  buildStart(inputOptions) {
1791
1880
  entries = Array.isArray(inputOptions.input) ? inputOptions.input : Object.values(inputOptions.input);
1792
1881
  },
1882
+ transform(code, id) {
1883
+ if (/\.vue$/.test(id)) {
1884
+ const { content, isTs, isJs } = compileVueCode(code);
1885
+ if (content) {
1886
+ if (isJs)
1887
+ hasJsVue = true;
1888
+ project.createSourceFile(id + (isTs ? ".ts" : ".js"), content, { overwrite: true });
1889
+ }
1890
+ } else if (!id.includes(".vue?vue") && (/\.tsx?$/.test(id) || allowJs && /\.jsx?$/.test(id))) {
1891
+ project.addSourceFileAtPath(id);
1892
+ }
1893
+ return null;
1894
+ },
1895
+ watchChange(id) {
1896
+ if (/\.(vue|(t|j)sx?)$/.test(id)) {
1897
+ isBundle = false;
1898
+ }
1899
+ },
1793
1900
  async closeBundle() {
1794
1901
  if (!outputDir || !project || isBundle)
1795
1902
  return;
1903
+ logger.info(import_chalk.default.green(`
1904
+ ${import_chalk.default.cyan("[vite:dts]")} Compiling source files...`));
1796
1905
  isBundle = true;
1797
- const allowJs = project.getCompilerOptions().allowJs;
1906
+ sourceDtsFiles.clear();
1798
1907
  const tsConfig = JSON.parse(await fs.readFile(tsConfigPath, "utf-8"));
1799
1908
  const include = options.include || tsConfig.include;
1800
1909
  const exclude = options.exclude || tsConfig.exclude;
1910
+ const includedFileSet = new Set();
1801
1911
  if (include && include.length) {
1802
1912
  const files = await glob(ensureArray(include).map(normalizeGlob), {
1803
1913
  cwd: root,
1804
1914
  absolute: true,
1805
1915
  ignore: ensureArray(exclude || ["node_modules/**"]).map(normalizeGlob)
1806
1916
  });
1807
- let index = 1;
1808
- let compiler;
1809
- const requireCompiler = () => {
1810
- if (!compiler) {
1811
- try {
1812
- compiler = __require("@vue/compiler-sfc");
1813
- } catch (e) {
1814
- throw new Error("@vue/compiler-sfc is not present in the dependency tree.\n");
1815
- }
1917
+ files.forEach((file) => {
1918
+ includedFileSet.add(/\.d\.tsx?$/.test(file) ? file : `${/\.(t|j)sx?$/.test(file) ? file.replace(/\.(t|j)sx?$/, "") : file}.d.ts`);
1919
+ if (/\.d\.tsx?$/.test(file)) {
1920
+ sourceDtsFiles.add(file);
1816
1921
  }
1817
- return compiler;
1818
- };
1819
- let hasJs = false;
1820
- await Promise.all(files.map(async (file) => {
1821
- if (/\.vue$/.test(file)) {
1822
- const { parse, compileScript } = requireCompiler();
1823
- const sfc = parse(await fs.readFile(file, "utf-8"));
1824
- const { script, scriptSetup } = sfc.descriptor;
1825
- if (script || scriptSetup) {
1826
- let content = "";
1827
- let isTs = false;
1828
- if (script && script.content) {
1829
- content += script.content;
1830
- if (script.lang === "ts") {
1831
- isTs = true;
1832
- } else if (!script.lang || script.lang === "js") {
1833
- hasJs = true;
1834
- }
1835
- }
1836
- if (scriptSetup) {
1837
- const compiled = compileScript(sfc.descriptor, {
1838
- id: `${index++}`
1839
- });
1840
- content += compiled.content;
1841
- if (scriptSetup.lang === "ts") {
1842
- isTs = true;
1843
- } else if (!scriptSetup.lang || scriptSetup.lang === "js") {
1844
- hasJs = true;
1845
- }
1846
- }
1847
- sourceFiles.push(project.createSourceFile(file + (isTs ? ".ts" : ".js"), content));
1848
- }
1849
- } else if (/\.tsx?$/.test(file) || allowJs && /\.jsx?$/.test(file)) {
1850
- sourceFiles.push(project.addSourceFileAtPath(file));
1851
- }
1852
- }));
1853
- if (hasJs) {
1922
+ });
1923
+ if (hasJsVue) {
1854
1924
  if (!allowJs) {
1855
- logger.warn(import_chalk.default.yellow("\n[vite:dts] Some js files are referenced, but you may not enable the 'allowJs' option.\n"));
1925
+ logger.warn(import_chalk.default.yellow(`${import_chalk.default.cyan("[vite:dts]")} Some js files are referenced, but you may not enable the 'allowJs' option.`));
1856
1926
  }
1857
1927
  project.compilerOptions.set({ allowJs: true });
1858
1928
  }
1859
1929
  }
1930
+ project.resolveSourceFileDependencies();
1860
1931
  const diagnostics = project.getPreEmitDiagnostics();
1861
- logger.warn(project.formatDiagnosticsWithColorAndContext(diagnostics));
1932
+ if ((diagnostics == null ? void 0 : diagnostics.length) && logDiagnostics) {
1933
+ logger.warn(project.formatDiagnosticsWithColorAndContext(diagnostics));
1934
+ }
1935
+ if (typeof afterDiagnostic === "function") {
1936
+ afterDiagnostic(diagnostics);
1937
+ }
1938
+ logger.info(import_chalk.default.green(`${import_chalk.default.cyan("[vite:dts]")} Generating declaration files...`));
1862
1939
  await runParallel(os.cpus().length, project.emitToMemory().getFiles(), async (outputFile) => {
1863
1940
  let filePath = outputFile.filePath;
1864
1941
  let content = outputFile.text;
1865
- if (clearPureImport && content === noneExport)
1942
+ const isMapFile = filePath.endsWith(".map");
1943
+ if (!includedFileSet.has(isMapFile ? filePath.slice(0, -4) : filePath) || clearPureImport && content === noneExport)
1866
1944
  return;
1867
- if (content !== noneExport) {
1945
+ if (!isMapFile && content !== noneExport) {
1868
1946
  content = clearPureImport ? removePureImport(content) : content;
1869
1947
  content = transformAliasImport(filePath, content, aliases);
1870
1948
  content = staticImport ? transformDynamicImport(content) : content;
@@ -1880,6 +1958,11 @@ var src_default = (options = {}) => {
1880
1958
  await fs.mkdir(dirname2(filePath), { recursive: true });
1881
1959
  await fs.writeFile(filePath, cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content, "utf8");
1882
1960
  });
1961
+ await Promise.all(Array.from(sourceDtsFiles).map(async (filePath) => {
1962
+ const targetPath = resolve2(outputDir, relative2(root, filePath));
1963
+ await fs.mkdir(dirname2(targetPath), { recursive: true });
1964
+ await fs.copyFile(filePath, targetPath);
1965
+ }));
1883
1966
  if (insertTypesEntry) {
1884
1967
  const pkgPath = resolve2(root, "package.json");
1885
1968
  const pkg = fs.existsSync(pkgPath) ? JSON.parse(await fs.readFile(pkgPath, "utf-8")) : {};
@@ -1894,9 +1977,11 @@ var src_default = (options = {}) => {
1894
1977
  await fs.writeFile(typesPath, content, "utf-8");
1895
1978
  }
1896
1979
  }
1980
+ logger.info(import_chalk.default.green(`${import_chalk.default.cyan("[vite:dts]")} Declaration files built.
1981
+ `));
1897
1982
  }
1898
1983
  };
1899
- };
1984
+ }
1900
1985
  export {
1901
- src_default as default
1986
+ dtsPlugin as default
1902
1987
  };
package/package.json CHANGED
@@ -11,36 +11,36 @@
11
11
  "ts-morph": "^11.0.3"
12
12
  },
13
13
  "devDependencies": {
14
- "@commitlint/cli": "^12.1.4",
15
- "@commitlint/config-conventional": "^12.1.4",
14
+ "@commitlint/cli": "^13.1.0",
15
+ "@commitlint/config-conventional": "^13.1.0",
16
16
  "@types/fs-extra": "^9.0.12",
17
- "@types/jest": "^26.0.24",
18
- "@typescript-eslint/eslint-plugin": "^4.28.4",
19
- "@typescript-eslint/parser": "^4.28.4",
20
- "@vitejs/plugin-vue": "^1.2.5",
21
- "@vue/compiler-sfc": "^3.1.5",
22
- "chalk": "^4.1.1",
17
+ "@types/jest": "^27.0.1",
18
+ "@typescript-eslint/eslint-plugin": "^4.29.2",
19
+ "@typescript-eslint/parser": "^4.29.2",
20
+ "@vitejs/plugin-vue": "^1.4.0",
21
+ "@vue/compiler-sfc": "^3.2.7",
22
+ "chalk": "^4.1.2",
23
23
  "commitizen": "^4.2.4",
24
24
  "conventional-changelog-cli": "^2.1.1",
25
25
  "cz-customizable": "^6.3.0",
26
26
  "enquirer": "^2.3.6",
27
- "eslint": "^7.31.0",
27
+ "eslint": "^7.32.0",
28
28
  "execa": "^5.1.1",
29
29
  "husky": "^7.0.1",
30
30
  "is-ci": "^3.0.0",
31
31
  "jest": "^27.0.6",
32
- "lint-staged": "^11.0.1",
32
+ "lint-staged": "^11.1.2",
33
33
  "minimist": "^1.2.5",
34
34
  "pinst": "^2.1.6",
35
35
  "prettier": "^2.3.2",
36
36
  "pretty-quick": "^3.1.1",
37
37
  "rimraf": "^3.0.2",
38
38
  "semver": "^7.3.5",
39
- "ts-jest": "^27.0.4",
40
- "tsup": "^4.12.5",
39
+ "ts-jest": "^27.0.5",
40
+ "tsup": "^4.14.0",
41
41
  "typescript": "4.3.5",
42
42
  "vite": "^2.4.3",
43
- "vue": "^3.1.1"
43
+ "vue": "^3.2.7"
44
44
  },
45
45
  "engines": {
46
46
  "node": ">=12.0.0"
@@ -60,7 +60,7 @@
60
60
  "module": "dist/index.mjs",
61
61
  "name": "vite-plugin-dts",
62
62
  "peerDependencies": {
63
- "vite": ">=2.3.7"
63
+ "vite": ">=2.4.4"
64
64
  },
65
65
  "repository": {
66
66
  "type": "git",
@@ -81,5 +81,5 @@
81
81
  "test:e2e": "cd example && vite build"
82
82
  },
83
83
  "types": "dist/index.d.ts",
84
- "version": "0.5.3"
84
+ "version": "0.8.1"
85
85
  }