rsbuild-plugin-dts 0.10.6 → 0.11.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
@@ -136,6 +136,25 @@ pluginDts({
136
136
  });
137
137
  ```
138
138
 
139
+ ### alias
140
+
141
+ - **Type:** `Record<string, string>`
142
+ - **Default:** `{}`
143
+
144
+ Configure the path alias for declaration files.
145
+
146
+ `alias` will be merged with `compilerOptions.paths` configured in `tsconfig.json` and `alias` has a higher priority.
147
+
148
+ In most cases, you don't need to use `alias`, but consider using it when you need to use path alias only in declaration files without wanting to affect JavaScript outputs. For example, map the declaration file of `foo` to `./compiled/foo`.
149
+
150
+ ```js
151
+ pluginDts({
152
+ alias: {
153
+ foo: './compiled/foo',
154
+ },
155
+ });
156
+ ```
157
+
139
158
  ### autoExternal
140
159
 
141
160
  - **Type:** `boolean`
package/dist/dts.js CHANGED
@@ -3,7 +3,7 @@ import { basename, dirname, isAbsolute, join, normalize, relative, resolve } fro
3
3
  import { logger } from "@rsbuild/core";
4
4
  import picocolors from "picocolors";
5
5
  import { emitDts } from "./tsc.js";
6
- import { calcLongestCommonPath, ensureTempDeclarationDir } from "./utils.js";
6
+ import { calcLongestCommonPath, ensureTempDeclarationDir, mergeAliasWithTsConfigPaths } from "./utils.js";
7
7
  const isObject = (obj)=>'[object Object]' === Object.prototype.toString.call(obj);
8
8
  const calcBundledPackages = (options)=>{
9
9
  const { cwd, autoExternal, userExternals, overrideBundledPackages } = options;
@@ -53,20 +53,19 @@ const calcBundledPackages = (options)=>{
53
53
  return Array.from(new Set(bundledPackages));
54
54
  };
55
55
  async function generateDts(data) {
56
- const { bundle, dtsEntry, dtsEmitPath, tsconfigPath, tsConfigResult, name, cwd, build, isWatch, dtsExtension = '.d.ts', autoExternal = true, userExternals, apiExtractorOptions, banner, footer, redirect = {
56
+ const { bundle, dtsEntry, dtsEmitPath, tsconfigPath, tsConfigResult, name, cwd, build, isWatch, dtsExtension = '.d.ts', autoExternal = true, alias = {}, userExternals, apiExtractorOptions, banner, footer, redirect = {
57
57
  path: true,
58
58
  extension: false
59
59
  } } = data;
60
60
  if (!isWatch) logger.start(`generating declaration files... ${picocolors.gray(`(${name})`)}`);
61
+ const paths = mergeAliasWithTsConfigPaths(tsConfigResult.options.paths, alias);
62
+ if (Object.keys(paths).length > 0) tsConfigResult.options.paths = paths;
61
63
  const { options: rawCompilerOptions, fileNames } = tsConfigResult;
62
64
  const rootDir = rawCompilerOptions.rootDir ?? (rawCompilerOptions.composite ? dirname(tsconfigPath) : await calcLongestCommonPath(fileNames.filter((fileName)=>!/\.d\.(ts|mts|cts)$/.test(fileName)))) ?? dirname(tsconfigPath);
63
65
  const resolvedDtsEmitPath = normalize(resolve(dirname(tsconfigPath), dtsEmitPath));
64
66
  if (build) {
65
67
  if (bundle) throw Error('Can not set "dts.bundle: true" when "dts.build: true"');
66
- if ((!rawCompilerOptions.outDir || normalize(rawCompilerOptions.outDir) !== resolvedDtsEmitPath) && (!rawCompilerOptions.declarationDir || normalize(rawCompilerOptions.declarationDir) !== resolvedDtsEmitPath)) {
67
- const info = rawCompilerOptions.outDir && !rawCompilerOptions.declarationDir ? 'outDir' : 'declarationDir';
68
- throw Error(`Please set ${info}: "${dtsEmitPath}" in ${picocolors.underline(tsconfigPath)} to keep it same as "dts.distPath" or "output.distPath.root" field in lib config.`);
69
- }
68
+ if ((!rawCompilerOptions.outDir || normalize(rawCompilerOptions.outDir) !== resolvedDtsEmitPath) && (!rawCompilerOptions.declarationDir || normalize(rawCompilerOptions.declarationDir) !== resolvedDtsEmitPath)) throw Error(`Please set "declarationDir": "${dtsEmitPath}" in ${picocolors.underline(tsconfigPath)} to keep it same as "dts.distPath" or "output.distPath.root" field in lib config.`);
70
69
  }
71
70
  const declarationDir = bundle ? ensureTempDeclarationDir(cwd, name) : dtsEmitPath;
72
71
  let dtsEntries = [];
@@ -114,6 +113,7 @@ async function generateDts(data) {
114
113
  dtsExtension,
115
114
  redirect,
116
115
  rootDir,
116
+ paths,
117
117
  banner,
118
118
  footer
119
119
  }, onComplete, bundle, isWatch, build);
package/dist/index.d.ts CHANGED
@@ -13,6 +13,7 @@ export type PluginDtsOptions = {
13
13
  build?: boolean;
14
14
  abortOnError?: boolean;
15
15
  dtsExtension?: string;
16
+ alias?: Record<string, string>;
16
17
  autoExternal?: boolean | {
17
18
  dependencies?: boolean;
18
19
  optionalDependencies?: boolean;
package/dist/index.js CHANGED
@@ -21,6 +21,7 @@ const pluginDts = (options = {})=>({
21
21
  options.redirect = options.redirect ?? {};
22
22
  options.redirect.path = options.redirect.path ?? true;
23
23
  options.redirect.extension = options.redirect.extension ?? false;
24
+ options.alias = options.alias ?? {};
24
25
  const dtsPromises = [];
25
26
  let promisesResult = [];
26
27
  let childProcesses = [];
package/dist/tsc.d.ts CHANGED
@@ -9,6 +9,7 @@ export type EmitDtsOptions = {
9
9
  dtsExtension: string;
10
10
  rootDir: string;
11
11
  redirect: DtsRedirect;
12
+ paths: Record<string, string[]>;
12
13
  banner?: string;
13
14
  footer?: string;
14
15
  };
package/dist/tsc.js CHANGED
@@ -8,7 +8,7 @@ const formatHost = {
8
8
  getCurrentDirectory: typescript.sys.getCurrentDirectory,
9
9
  getNewLine: ()=>typescript.sys.newLine
10
10
  };
11
- async function handleDiagnosticsAndProcessFiles(diagnostics, configPath, bundle, declarationDir, dtsExtension, redirect, rootDir, banner, footer, name) {
11
+ async function handleDiagnosticsAndProcessFiles(diagnostics, configPath, bundle, declarationDir, dtsExtension, redirect, rootDir, paths, banner, footer, name) {
12
12
  const diagnosticMessages = [];
13
13
  for (const diagnostic of diagnostics){
14
14
  const message = typescript.formatDiagnosticsWithColorAndContext([
@@ -16,7 +16,7 @@ async function handleDiagnosticsAndProcessFiles(diagnostics, configPath, bundle,
16
16
  ], formatHost);
17
17
  diagnosticMessages.push(message);
18
18
  }
19
- await processDtsFiles(bundle, declarationDir, dtsExtension, redirect, configPath, rootDir, banner, footer);
19
+ await processDtsFiles(bundle, declarationDir, dtsExtension, redirect, configPath, rootDir, paths, banner, footer);
20
20
  if (diagnosticMessages.length) {
21
21
  for (const message of diagnosticMessages)logger.error(logPrefixTsc, message);
22
22
  const error = new Error(`Failed to generate declaration files. ${picocolors.gray(`(${name})`)}`);
@@ -26,7 +26,7 @@ async function handleDiagnosticsAndProcessFiles(diagnostics, configPath, bundle,
26
26
  }
27
27
  async function emitDts(options, onComplete, bundle = false, isWatch = false, build = false) {
28
28
  const start = Date.now();
29
- const { configPath, tsConfigResult, declarationDir, name, dtsExtension, rootDir, banner, footer, redirect } = options;
29
+ const { configPath, tsConfigResult, declarationDir, name, dtsExtension, rootDir, banner, footer, paths, redirect } = options;
30
30
  const { options: rawCompilerOptions, fileNames, projectReferences } = tsConfigResult;
31
31
  const compilerOptions = {
32
32
  ...rawCompilerOptions,
@@ -51,11 +51,11 @@ async function emitDts(options, onComplete, bundle = false, isWatch = false, bui
51
51
  logger.info(logPrefixTsc, message);
52
52
  onComplete(true);
53
53
  }
54
- await processDtsFiles(bundle, declarationDir, dtsExtension, redirect, configPath, rootDir, banner, footer);
54
+ await processDtsFiles(bundle, declarationDir, dtsExtension, redirect, configPath, rootDir, paths, banner, footer);
55
55
  }
56
56
  if (6193 === diagnostic.code) {
57
57
  logger.error(logPrefixTsc, message);
58
- await processDtsFiles(bundle, declarationDir, dtsExtension, redirect, configPath, rootDir, banner, footer);
58
+ await processDtsFiles(bundle, declarationDir, dtsExtension, redirect, configPath, rootDir, paths, banner, footer);
59
59
  }
60
60
  };
61
61
  const renameDtsFile = (fileName)=>{
@@ -102,7 +102,7 @@ async function emitDts(options, onComplete, bundle = false, isWatch = false, bui
102
102
  const emitResult = program.emit();
103
103
  allDiagnostics.push(...emitResult.diagnostics);
104
104
  const sortAndDeduplicateDiagnostics = typescript.sortAndDeduplicateDiagnostics(allDiagnostics);
105
- await handleDiagnosticsAndProcessFiles(sortAndDeduplicateDiagnostics, configPath, bundle, declarationDir, dtsExtension, redirect, rootDir, banner, footer, name);
105
+ await handleDiagnosticsAndProcessFiles(sortAndDeduplicateDiagnostics, configPath, bundle, declarationDir, dtsExtension, redirect, rootDir, paths, banner, footer, name);
106
106
  } else {
107
107
  let errorNumber = 0;
108
108
  const reportErrorSummary = (errorCount)=>{
@@ -113,7 +113,7 @@ async function emitDts(options, onComplete, bundle = false, isWatch = false, bui
113
113
  configPath
114
114
  ], compilerOptions);
115
115
  solutionBuilder.build();
116
- await processDtsFiles(bundle, declarationDir, dtsExtension, redirect, configPath, rootDir, banner, footer);
116
+ await processDtsFiles(bundle, declarationDir, dtsExtension, redirect, configPath, rootDir, paths, banner, footer);
117
117
  if (errorNumber > 0) {
118
118
  const error = new Error(`Failed to generate declaration files. ${picocolors.gray(`(${name})`)}`);
119
119
  error.stack = '';
@@ -139,7 +139,7 @@ async function emitDts(options, onComplete, bundle = false, isWatch = false, bui
139
139
  const emitResult = program.emit();
140
140
  const allDiagnostics = preEmitDiagnostics.concat(emitResult.diagnostics);
141
141
  const sortAndDeduplicateDiagnostics = typescript.sortAndDeduplicateDiagnostics(allDiagnostics);
142
- await handleDiagnosticsAndProcessFiles(sortAndDeduplicateDiagnostics, configPath, bundle, declarationDir, dtsExtension, redirect, rootDir, banner, footer, name);
142
+ await handleDiagnosticsAndProcessFiles(sortAndDeduplicateDiagnostics, configPath, bundle, declarationDir, dtsExtension, redirect, rootDir, paths, banner, footer, name);
143
143
  }
144
144
  if (bundle) logger.info(`declaration files prepared in ${getTimeCost(start)} ${picocolors.gray(`(${name})`)}`);
145
145
  else logger.ready(`declaration files generated in ${getTimeCost(start)} ${picocolors.gray(`(${name})`)}`);
package/dist/utils.d.ts CHANGED
@@ -4,6 +4,7 @@ import ts from 'typescript';
4
4
  import type { DtsEntry, DtsRedirect } from './index';
5
5
  export declare const JS_EXTENSIONS_PATTERN: RegExp;
6
6
  export declare function loadTsconfig(tsconfigPath: string): ts.ParsedCommandLine;
7
+ export declare function mergeAliasWithTsConfigPaths(paths: Record<string, string[]> | undefined, alias?: Record<string, string>): Record<string, string[]>;
7
8
  export declare const TEMP_FOLDER = ".rslib";
8
9
  export declare const TEMP_DTS_DIR: string;
9
10
  export declare function ensureTempDeclarationDir(cwd: string, name: string): string;
@@ -16,7 +17,7 @@ export declare const prettyTime: (seconds: number) => string;
16
17
  export declare function getTimeCost(start: number): string;
17
18
  export declare function addBannerAndFooter(dtsFile: string, banner?: string, footer?: string): Promise<void>;
18
19
  export declare function redirectDtsImports(dtsFile: string, dtsExtension: string, redirect: DtsRedirect, matchPath: MatchPath, outDir: string, rootDir: string): Promise<void>;
19
- export declare function processDtsFiles(bundle: boolean, dir: string, dtsExtension: string, redirect: DtsRedirect, tsconfigPath: string, rootDir: string, banner?: string, footer?: string): Promise<void>;
20
+ export declare function processDtsFiles(bundle: boolean, dir: string, dtsExtension: string, redirect: DtsRedirect, tsconfigPath: string, rootDir: string, paths: Record<string, string[]>, banner?: string, footer?: string): Promise<void>;
20
21
  export declare function processSourceEntry(bundle: boolean, entryConfig: NonNullable<RsbuildConfig['source']>['entry']): DtsEntry[];
21
22
  export declare function calcLongestCommonPath(absPaths: string[]): Promise<string | null>;
22
23
  export declare const globDtsFiles: (dir: string, patterns: string[]) => Promise<string[]>;
package/dist/utils.js CHANGED
@@ -29,6 +29,22 @@ function loadTsconfig(tsconfigPath) {
29
29
  const configFileContent = typescript.parseJsonConfigFileContent(configFile.config, typescript.sys, node_path.dirname(tsconfigPath));
30
30
  return configFileContent;
31
31
  }
32
+ function mergeAliasWithTsConfigPaths(paths, alias = {}) {
33
+ const mergedPaths = {};
34
+ if (alias && 'object' == typeof alias && Object.keys(alias).length > 0) {
35
+ for (const [key, value] of Object.entries(alias))if ('string' == typeof value && value.trim()) mergedPaths[key] = [
36
+ value
37
+ ];
38
+ }
39
+ if (paths) {
40
+ for (const [key, value] of Object.entries(paths))if (Array.isArray(value) && value.length > 0) {
41
+ if (!mergedPaths[key]) mergedPaths[key] = [
42
+ ...value
43
+ ];
44
+ }
45
+ }
46
+ return Object.keys(mergedPaths).length > 0 ? mergedPaths : {};
47
+ }
32
48
  const TEMP_FOLDER = '.rslib';
33
49
  const TEMP_DTS_DIR = `${TEMP_FOLDER}/declarations`;
34
50
  function ensureTempDeclarationDir(cwd, name) {
@@ -227,13 +243,13 @@ async function redirectDtsImports(dtsFile, dtsExtension, redirect, matchPath, ou
227
243
  }
228
244
  if (code.hasChanged()) await promises.writeFile(dtsFile, code.toString());
229
245
  }
230
- async function processDtsFiles(bundle, dir, dtsExtension, redirect, tsconfigPath, rootDir, banner, footer) {
246
+ async function processDtsFiles(bundle, dir, dtsExtension, redirect, tsconfigPath, rootDir, paths, banner, footer) {
231
247
  if (bundle) return;
232
248
  let matchPath;
233
249
  if (redirect.path || redirect.extension) {
234
250
  const result = loadConfig(tsconfigPath);
235
251
  if ('failed' === result.resultType) return void logger.error(result.message);
236
- const { absoluteBaseUrl, paths, addMatchAll } = result;
252
+ const { absoluteBaseUrl, addMatchAll } = result;
237
253
  const mainFields = [];
238
254
  matchPath = createMatchPath(absoluteBaseUrl, paths, mainFields, addMatchAll);
239
255
  }
@@ -304,8 +320,12 @@ async function cleanDtsFiles(dir) {
304
320
  async function cleanTsBuildInfoFile(tsconfigPath, compilerOptions) {
305
321
  const tsconfigDir = dirname(tsconfigPath);
306
322
  const { outDir, rootDir, tsBuildInfoFile } = compilerOptions;
307
- let tsbuildInfoFilePath = `${basename(tsconfigPath, '.json')}${tsBuildInfoFile ?? '.tsbuildinfo'}`;
308
- if (outDir) tsbuildInfoFilePath = rootDir ? join(outDir, relative(resolve(tsconfigDir, rootDir), tsconfigDir), tsbuildInfoFilePath) : join(outDir, tsbuildInfoFilePath);
323
+ let tsbuildInfoFilePath;
324
+ if (tsBuildInfoFile && isAbsolute(tsBuildInfoFile)) tsbuildInfoFilePath = tsBuildInfoFile;
325
+ else {
326
+ const defaultFileName = `${basename(tsconfigPath, '.json')}${tsBuildInfoFile ?? '.tsbuildinfo'}`;
327
+ tsbuildInfoFilePath = outDir ? rootDir ? join(outDir, relative(resolve(tsconfigDir, rootDir), tsconfigDir), defaultFileName) : join(outDir, defaultFileName) : join(tsconfigDir, defaultFileName);
328
+ }
309
329
  if (await pathExists(tsbuildInfoFilePath)) await promises.rm(tsbuildInfoFilePath, {
310
330
  force: true
311
331
  });
@@ -321,4 +341,4 @@ function warnIfOutside(cwd, dir, label) {
321
341
  if (relDir.startsWith('..')) logger.warn(`The resolved ${label} ${picocolors.cyan(normalizedDir)} is outside the project root ${picocolors.cyan(normalizedCwd)}, please check your tsconfig file.`);
322
342
  }
323
343
  }
324
- export { JS_EXTENSIONS_PATTERN, TEMP_DTS_DIR, TEMP_FOLDER, addBannerAndFooter, calcLongestCommonPath, cleanDtsFiles, cleanTsBuildInfoFile, clearTempDeclarationDir, emptyDir, ensureTempDeclarationDir, getDtsEmitPath, getFileLoc, getTimeCost, globDtsFiles, isDirectory, loadTsconfig, pathExists, prettyTime, processDtsFiles, processSourceEntry, redirectDtsImports, warnIfOutside };
344
+ export { JS_EXTENSIONS_PATTERN, TEMP_DTS_DIR, TEMP_FOLDER, addBannerAndFooter, calcLongestCommonPath, cleanDtsFiles, cleanTsBuildInfoFile, clearTempDeclarationDir, emptyDir, ensureTempDeclarationDir, getDtsEmitPath, getFileLoc, getTimeCost, globDtsFiles, isDirectory, loadTsconfig, mergeAliasWithTsConfigPaths, pathExists, prettyTime, processDtsFiles, processSourceEntry, redirectDtsImports, warnIfOutside };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rsbuild-plugin-dts",
3
- "version": "0.10.6",
3
+ "version": "0.11.1",
4
4
  "description": "Rsbuild plugin that supports emitting declaration files for TypeScript.",
5
5
  "homepage": "https://rslib.rs",
6
6
  "bugs": {
@@ -32,11 +32,11 @@
32
32
  "tsconfig-paths": "^4.2.0"
33
33
  },
34
34
  "devDependencies": {
35
- "@microsoft/api-extractor": "^7.52.8",
36
- "@rsbuild/core": "~1.4.7",
35
+ "@microsoft/api-extractor": "^7.52.10",
36
+ "@rsbuild/core": "~1.4.12",
37
37
  "rsbuild-plugin-publint": "^0.3.2",
38
- "rslib": "npm:@rslib/core@0.10.5",
39
- "typescript": "^5.8.3",
38
+ "rslib": "npm:@rslib/core@0.11.0",
39
+ "typescript": "^5.9.2",
40
40
  "@rslib/tsconfig": "0.0.1"
41
41
  },
42
42
  "peerDependencies": {