rsbuild-plugin-dts
Version:
Rsbuild plugin that supports emitting declaration files for TypeScript.
133 lines (132 loc) • 6.83 kB
JavaScript
import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__ from "@rsbuild/core";
import * as __WEBPACK_EXTERNAL_MODULE_picocolors__ from "picocolors";
import * as __WEBPACK_EXTERNAL_MODULE__tsc_js_1050029c__ from "./tsc.js";
import * as __WEBPACK_EXTERNAL_MODULE__utils_js_d88b7fe1__ from "./utils.js";
const isObject = (obj)=>'[object Object]' === Object.prototype.toString.call(obj);
const calcBundledPackages = (options)=>{
const { autoExternal, cwd, userExternals } = options;
let pkgJson;
try {
const content = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readFileSync((0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(cwd, 'package.json'), 'utf-8');
pkgJson = JSON.parse(content);
} catch (err) {
__WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__.logger.warn('The type of third-party packages will not be bundled due to read package.json failed');
return [];
}
const externalOptions = autoExternal ? {
dependencies: true,
peerDependencies: true,
optionalDependencies: true,
devDependencies: false,
...true === autoExternal ? {} : autoExternal
} : {
dependencies: false,
peerDependencies: false,
devDependencies: false
};
const getUserExternalsKeys = (value)=>{
if (!value) return [];
if ('string' == typeof value || value instanceof RegExp) return [
value
];
if (Array.isArray(value)) return value.flatMap((v)=>getUserExternalsKeys(v));
if (isObject(userExternals)) return Object.keys(userExternals);
return [];
};
const externals = getUserExternalsKeys(userExternals);
const allDeps = [];
for (const type of [
'dependencies',
'peerDependencies',
'devDependencies'
]){
const deps = pkgJson[type] && Object.keys(pkgJson[type]);
if (deps) {
if (externalOptions[type]) externals.push(...deps);
allDeps.push(...deps);
}
}
const bundledPackages = allDeps.filter((d)=>!externals.some((e)=>'string' == typeof e ? d === e : e.test(d)));
return Array.from(new Set(bundledPackages));
};
async function generateDts(data) {
const { bundle, dtsEntry, dtsEmitPath, tsconfigPath, tsConfigResult, name, cwd, build, isWatch, dtsExtension = '.d.ts', autoExternal = true, userExternals, banner, footer, redirect = {
path: true,
extension: false
} } = data;
__WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__.logger.start(`Generating DTS... ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].gray(`(${name})`)}`);
const { options: rawCompilerOptions, fileNames } = tsConfigResult;
const rootDir = rawCompilerOptions.rootDir ?? (rawCompilerOptions.composite ? (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.dirname)(tsconfigPath) : await (0, __WEBPACK_EXTERNAL_MODULE__utils_js_d88b7fe1__.calcLongestCommonPath)(fileNames.filter((fileName)=>!/\.d\.(ts|mts|cts)$/.test(fileName)))) ?? (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.dirname)(tsconfigPath);
const resolvedDtsEmitPath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.normalize)((0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.resolve)((0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.dirname)(tsconfigPath), dtsEmitPath));
if (build) {
if (bundle) throw Error('Can not set "dts.bundle: true" when "dts.build: true"');
if ((!rawCompilerOptions.outDir || (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.normalize)(rawCompilerOptions.outDir) !== resolvedDtsEmitPath) && (!rawCompilerOptions.declarationDir || (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.normalize)(rawCompilerOptions.declarationDir) !== resolvedDtsEmitPath)) {
const info = rawCompilerOptions.outDir && !rawCompilerOptions.declarationDir ? 'outDir' : 'declarationDir';
throw Error(`Please set ${info}: "${dtsEmitPath}" in ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].underline(tsconfigPath)} to keep it same as "dts.distPath" or "output.distPath.root" field in lib config.`);
}
}
const declarationDir = bundle ? (0, __WEBPACK_EXTERNAL_MODULE__utils_js_d88b7fe1__.ensureTempDeclarationDir)(cwd, name) : dtsEmitPath;
let dtsEntries = [];
if (true === bundle) dtsEntries = dtsEntry.map((entryObj)=>{
const { name: entryName, path: entryPath } = entryObj;
if (!entryPath) return null;
const entrySourcePath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.isAbsolute)(entryPath) ? entryPath : (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(cwd, entryPath);
const relativePath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.relative)(rootDir, (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.dirname)(entrySourcePath));
const newPath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(declarationDir, relativePath, (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.basename)(entrySourcePath)).replace(/\?.*$/, '').replace(/\.(js|mjs|jsx|ts|mts|tsx|cjs|cts|cjsx|ctsx|mjsx|mtsx)$/, '.d.ts');
return {
name: entryName,
path: newPath
};
}).filter(Boolean);
const bundleDtsIfNeeded = async ()=>{
if (true === bundle) {
const { bundleDts } = await import("./apiExtractor.js");
await bundleDts({
name,
cwd,
distPath: dtsEmitPath,
dtsEntry: dtsEntries,
tsconfigPath,
dtsExtension,
banner,
footer,
bundledPackages: calcBundledPackages({
autoExternal,
cwd,
userExternals
})
});
}
};
const onComplete = async (isSuccess)=>{
if (isSuccess) await bundleDtsIfNeeded();
};
await (0, __WEBPACK_EXTERNAL_MODULE__tsc_js_1050029c__.emitDts)({
name,
cwd,
configPath: tsconfigPath,
tsConfigResult,
declarationDir,
dtsExtension,
redirect,
rootDir,
banner,
footer
}, onComplete, bundle, isWatch, build);
if (!isWatch) await bundleDtsIfNeeded();
}
process.on('message', async (data)=>{
if (!data.cwd) return;
try {
await generateDts(data);
} catch (e) {
__WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__.logger.error(e);
process.send('error');
process.exit(1);
}
process.send('success');
if (!data.isWatch) process.exit();
});
export { calcBundledPackages, generateDts };