Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/core/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1416,6 +1416,7 @@ const composeDtsConfig = async (
abortOnError: dts?.abortOnError,
dtsExtension: dts?.autoExtension ? dtsExtension : '.d.ts',
autoExternal: getAutoExternalDefaultValue(format, autoExternal),
alias: dts?.alias,
banner: banner?.dts,
footer: footer?.dts,
redirect: redirect?.dts,
Expand Down
6 changes: 6 additions & 0 deletions packages/core/src/types/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,12 @@ export type Dts =
* @see {@link https://rslib.rs/config/lib/dts#dtsautoextension}
*/
autoExtension?: boolean;
// Set the alias for the module path, similar to the `paths` option in `tsconfig.json`.
/**
* @defaultValue `{}`
* @see {@link https://rslib.rs/config/lib/dts#dtsalias}
*/
alias?: Record<string, string>;
}
| boolean;

Expand Down
19 changes: 19 additions & 0 deletions packages/plugin-dts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,25 @@ pluginDts({
});
```

### alias

- **Type:**` Record<string, string>`
- **Default:** `{}`

Configure the path alias for declaration files.

`alias` will be merged with `compilerOptions.paths` configured in `tsconfig.json` and `alias` has a higher priority.

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`.

```js
pluginDts({
alias: {
foo: './compiled/foo',
},
});
```

### autoExternal

- **Type:** `boolean`
Expand Down
17 changes: 16 additions & 1 deletion packages/plugin-dts/src/dts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ import { logger } from '@rsbuild/core';
import color from 'picocolors';
import type { DtsEntry, DtsGenOptions } from './index';
import { emitDts } from './tsc';
import { calcLongestCommonPath, ensureTempDeclarationDir } from './utils';
import {
calcLongestCommonPath,
ensureTempDeclarationDir,
mergeAliasWithTsConfigPaths,
} from './utils';

const isObject = (obj: unknown): obj is Record<string, any> =>
Object.prototype.toString.call(obj) === '[object Object]';
Expand Down Expand Up @@ -123,6 +127,7 @@ export async function generateDts(data: DtsGenOptions): Promise<void> {
isWatch,
dtsExtension = '.d.ts',
autoExternal = true,
alias = {},
userExternals,
apiExtractorOptions,
banner,
Expand All @@ -136,6 +141,15 @@ export async function generateDts(data: DtsGenOptions): Promise<void> {
logger.start(`generating declaration files... ${color.gray(`(${name})`)}`);
}

// merge alias and tsconfig paths
const paths = mergeAliasWithTsConfigPaths(
tsConfigResult.options.paths,
alias,
);
if (Object.keys(paths).length > 0) {
tsConfigResult.options.paths = paths;
}

const { options: rawCompilerOptions, fileNames } = tsConfigResult;

// The longest common path of all non-declaration input files.
Expand Down Expand Up @@ -240,6 +254,7 @@ export async function generateDts(data: DtsGenOptions): Promise<void> {
dtsExtension,
redirect,
rootDir,
paths,
banner,
footer,
},
Expand Down
2 changes: 2 additions & 0 deletions packages/plugin-dts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export type PluginDtsOptions = {
build?: boolean;
abortOnError?: boolean;
dtsExtension?: string;
alias?: Record<string, string>;
autoExternal?:
| boolean
| {
Expand Down Expand Up @@ -91,6 +92,7 @@ export const pluginDts = (options: PluginDtsOptions = {}): RsbuildPlugin => ({
options.redirect = options.redirect ?? {};
options.redirect.path = options.redirect.path ?? true;
options.redirect.extension = options.redirect.extension ?? false;
options.alias = options.alias ?? {};

const dtsPromises: Promise<TaskResult>[] = [];
let promisesResult: TaskResult[] = [];
Expand Down
9 changes: 9 additions & 0 deletions packages/plugin-dts/src/tsc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export type EmitDtsOptions = {
dtsExtension: string;
rootDir: string;
redirect: DtsRedirect;
paths: Record<string, string[]>;
banner?: string;
footer?: string;
};
Expand All @@ -33,6 +34,7 @@ async function handleDiagnosticsAndProcessFiles(
dtsExtension: string,
redirect: DtsRedirect,
rootDir: string,
paths: Record<string, string[]>,
banner?: string,
footer?: string,
name?: string,
Expand All @@ -54,6 +56,7 @@ async function handleDiagnosticsAndProcessFiles(
redirect,
configPath,
rootDir,
paths,
banner,
footer,
);
Expand Down Expand Up @@ -89,6 +92,7 @@ export async function emitDts(
rootDir,
banner,
footer,
paths,
redirect,
} = options;
const {
Expand Down Expand Up @@ -147,6 +151,7 @@ export async function emitDts(
redirect,
configPath,
rootDir,
paths,
banner,
footer,
);
Expand All @@ -162,6 +167,7 @@ export async function emitDts(
redirect,
configPath,
rootDir,
paths,
banner,
footer,
);
Expand Down Expand Up @@ -230,6 +236,7 @@ export async function emitDts(
dtsExtension,
redirect,
rootDir,
paths,
banner,
footer,
name,
Expand Down Expand Up @@ -291,6 +298,7 @@ export async function emitDts(
dtsExtension,
redirect,
rootDir,
paths,
banner,
footer,
name,
Expand Down Expand Up @@ -326,6 +334,7 @@ export async function emitDts(
redirect,
configPath,
rootDir,
paths,
banner,
footer,
);
Expand Down
30 changes: 28 additions & 2 deletions packages/plugin-dts/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,31 @@ export function loadTsconfig(tsconfigPath: string): ts.ParsedCommandLine {
return configFileContent;
}

export function mergeAliasWithTsConfigPaths(
paths: Record<string, string[]> | undefined,
alias: Record<string, string> = {},
): Record<string, string[]> {
const mergedPaths: Record<string, string[]> = {};

if (paths) {
for (const [key, value] of Object.entries(paths)) {
if (Array.isArray(value) && value.length > 0) {
mergedPaths[key] = [...value];
}
}
}

if (alias && typeof alias === 'object' && Object.keys(alias).length > 0) {
for (const [key, value] of Object.entries(alias)) {
if (typeof value === 'string' && value.trim()) {
mergedPaths[key] = [value];
}
}
}

return Object.keys(mergedPaths).length > 0 ? mergedPaths : {};
}

export const TEMP_FOLDER = '.rslib';
export const TEMP_DTS_DIR: string = `${TEMP_FOLDER}/declarations`;

Expand Down Expand Up @@ -395,6 +420,7 @@ export async function processDtsFiles(
redirect: DtsRedirect,
tsconfigPath: string,
rootDir: string,
paths: Record<string, string[]>,
banner?: string,
footer?: string,
): Promise<void> {
Expand All @@ -412,11 +438,11 @@ export async function processDtsFiles(
return;
}

const { absoluteBaseUrl, paths, addMatchAll } = result;
const { absoluteBaseUrl, addMatchAll } = result;
const mainFields: string[] = [];
/**
* resolve paths priorities:
* see https://github.com/jonaskello/tsconfig-paths/blob/098e066632f5b9f35c956803fe60d17ffc60b688/src/match-path-sync.ts#L18-L26
* see https://github.com/jonaskello/tsconfig-paths/blob/098e066632f5b9f35c956803fe60d17ffc60b688/src/try-path.ts#L11-L17
*/
matchPath = createMatchPath(
absoluteBaseUrl,
Expand Down
11 changes: 11 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export declare function logger(): {
(...data: any[]): void;
(message?: any, ...optionalParams: any[]): void;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function logger() {
return console.log;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "express",
"version": "0.0.0",
"private": true
}
10 changes: 10 additions & 0 deletions tests/integration/dts/bundle-false/alias/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "dts-bundle-false-alias-test",
"version": "1.0.0",
"private": true,
"type": "module",
"devDependencies": {
"@types/express": "^5.0.3",
"express": "^5.1.0"
}
}
23 changes: 23 additions & 0 deletions tests/integration/dts/bundle-false/alias/rslib.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { defineConfig } from '@rslib/core';
import { generateBundleCjsConfig, generateBundleEsmConfig } from 'test-helper';

export default defineConfig({
lib: [
generateBundleEsmConfig({
dts: {
bundle: false,
alias: {
express: './compile/express',
},
},
}),
generateBundleCjsConfig({
dts: {
bundle: false,
alias: {
express: './compile/express',
},
},
}),
],
});
1 change: 1 addition & 0 deletions tests/integration/dts/bundle-false/alias/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {} from 'express';
7 changes: 7 additions & 0 deletions tests/integration/dts/bundle-false/alias/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"compilerOptions": {
"strict": true,
"skipLibCheck": true
},
"include": ["src/**/*"]
}
27 changes: 27 additions & 0 deletions website/docs/en/config/lib/dts.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ type Dts =
build?: boolean;
abortOnError?: boolean;
autoExtension?: boolean;
alias?: Record<string, string>;
}
| boolean;
```
Expand Down Expand Up @@ -218,3 +219,29 @@ When `dts.autoExtension` is set to `true`, the declaration file extension will b
It follows the same logic as [lib.autoExtension](/config/lib/auto-extension), but the default value is different since the declaration file extension may cause some issues with different module resolution strategies.

:::

### dts.alias

- **Type:**` Record<string, string>`
- **Default:** `{}`

Configure the path alias for declaration files.

`dts.alias` will be merged with `compilerOptions.paths` configured in `tsconfig.json` and `dts.alias` has a higher priority.

In most cases, you don't need to use `dts.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`.

```ts title="rslib.config.ts"
export default {
lib: [
{
// [!code highlight:5]
dts: {
alias: {
foo: './compiled/foo',
},
},
},
],
};
```
1 change: 1 addition & 0 deletions website/docs/en/guide/advanced/dts.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ The priority from highest to lowest of final output directory of declaration fil
| [dts.build](/config/lib/dts#dtsbuild) | Whether to generate declaration files with building the project references. |
| [dts.abortOnError](/config/lib/dts#dtsabortonerror) | Whether to abort the build process when an error occurs during declaration files generation. |
| [dts.autoExtension](/config/lib/dts#dtsautoextension) | Whether to automatically set the declaration file extension based on the [format](/config/lib/format) option. |
| [dts.alias](/config/lib/dts#dtsalias) | The path alias of the declaration files. |
| [banner.dts](/config/lib/banner#bannerdts) | Inject content into the top of each declaration output file. |
| [footer.dts](/config/lib/footer#footerdts) | Inject content into the bottom of each declaration file. |
| [redirect.dts.path](/config/lib/redirect#redirectdtspath) | Whether to automatically redirect the import paths of TypeScript declaration output files. |
Expand Down
27 changes: 27 additions & 0 deletions website/docs/zh/config/lib/dts.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ type Dts =
build?: boolean;
abortOnError?: boolean;
autoExtension?: boolean;
alias?: Record<string, string>;
}
| boolean;
```
Expand Down Expand Up @@ -218,3 +219,29 @@ export default {
这遵循与 [lib.autoExtension](/config/lib/auto-extension) 相同的逻辑,但默认值不同,因为类型声明文件扩展名可能会在不同的模块解析策略中造成一些问题。

:::

### dts.alias

- **类型:** `Record<string, string>`
- **默认值:** `{}`

用于配置类型声明文件的路径别名。

`dts.alias` 会与 `tsconfig.json` 中配置的 `compilerOptions.paths` 合并,且 `dts.alias` 具有更高的优先级。

大部分情况下,你不需要使用 `dts.alias`,但当你需要在类型声明文件中使用路径别名却不希望影响 JavaScript 产物时,可以考虑使用它。比如,将 `foo` 的类型声明文件指向 `./compiled/foo`。

```ts title="rslib.config.ts"
export default {
lib: [
{
// [!code highlight:5]
dts: {
alias: {
foo: './compiled/foo',
},
},
},
],
};
```
Loading
Loading