Skip to content

Commit

Permalink
feat: add oxc-transform as optional declaration generator
Browse files Browse the repository at this point in the history
  • Loading branch information
XGHeaven committed Nov 15, 2024
1 parent 073a6cb commit 7a6f343
Show file tree
Hide file tree
Showing 9 changed files with 404 additions and 283 deletions.
5 changes: 5 additions & 0 deletions .changeset/friendly-radios-walk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@ice/pkg': minor
---

feat: add oxc-transform as optional declaration generator
3 changes: 3 additions & 0 deletions examples/react-component/build.config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ export default defineConfig({
formats: ['esm', 'es2017', 'cjs'],
},
jsxRuntime: 'classic',
declaration: {
generator: 'oxc'

Check failure on line 13 in examples/react-component/build.config.mts

View workflow job for this annotation

GitHub Actions / CI (18)

Missing trailing comma
},
sourceMaps: false,
bundle: {
formats: ['esm', 'es2017'],
Expand Down
3 changes: 2 additions & 1 deletion packages/pkg/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
"gzip-size": "^7.0.0",
"lodash.merge": "^4.6.2",
"magic-string": "^0.25.7",
"oxc-transform": "^0.35.0",
"picocolors": "^1.0.0",
"postcss": "^8.4.31",
"postcss-plugin-rpx2vw": "^1.0.0",
Expand All @@ -69,7 +70,7 @@
"rollup-plugin-visualizer": "^5.12.0",
"semver": "^7.5.2",
"tsc-alias": "^1.8.2",
"typescript": "^4.9.5"
"typescript": "^5.6.0"
},
"devDependencies": {
"@types/babel__core": "^7.1.20",
Expand Down
83 changes: 55 additions & 28 deletions packages/pkg/src/helpers/dts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export interface DtsCompileOptions {
alias: TaskConfig['alias'];
rootDir: string;
outputDir: string;
usingOxc: boolean;
}

function formatAliasToTSPathsConfig(alias: TaskConfig['alias']) {
Expand Down Expand Up @@ -116,7 +117,7 @@ async function getProjectTSConfig(rootDir: string): Promise<ts.ParsedCommandLine
};
}

export async function dtsCompile({ files, rootDir, outputDir, alias }: DtsCompileOptions): Promise<DtsInputFile[]> {
export async function dtsCompile({ files, rootDir, outputDir, alias, usingOxc }: DtsCompileOptions): Promise<DtsInputFile[]> {
if (!files.length) {
return [];
}
Expand All @@ -132,18 +133,53 @@ export async function dtsCompile({ files, rootDir, outputDir, alias }: DtsCompil
dtsPath: normalizePath(dtsPath),
}));

const compileFunction = usingOxc ? compileFromOxc : compileFromTsc;
const dtsFiles = await compileFunction(_files, tsConfig)

if (!Object.keys(alias).length) {
// no alias config
return _files.map((file) => ({
...file,
dtsContent: dtsFiles[file.dtsPath],
}));
}

// We use tsc-alias to resolve d.ts alias.
// Reason: https://github.com/microsoft/TypeScript/issues/30952#issuecomment-1114225407
const tsConfigLocalPath = path.join(rootDir, 'node_modules/.cache/ice-pkg/tsconfig.json');
await fse.ensureFile(tsConfigLocalPath);
await fse.writeJSON(tsConfigLocalPath, {
...tsConfig,
compilerOptions: tsConfig.options,
}, { spaces: 2 });

const runFile = await prepareSingleFileReplaceTscAliasPaths({
configFile: tsConfigLocalPath,
outDir: outputDir,
});

const result = _files.map((file) => ({
...file,
dtsContent: dtsFiles[file.dtsPath] ? runFile({ fileContents: dtsFiles[file.dtsPath], filePath: file.dtsPath }) : '',
}));

return result;
}

async function compileFromTsc(files: DtsInputFile[], tsConfig: ts.ParsedCommandLine): Promise<Record<string, string>> {
// In order to only include the update files instead of all the files in the watch mode.
function getProgramRootNames(originalFilenames: string[]) {
// Should include all the resolved .d.ts file to avoid dts generate error:
// TS4025: Exported variable '<name>' has or is using private name '<name>'.
const dtsFilenames = originalFilenames.filter((filename) => filename.endsWith('.d.ts'));
const needCompileFileNames = _files.map(({ filePath }) => filePath);
const needCompileFileNames = files.map(({ filePath }) => filePath);
return [...needCompileFileNames, ...dtsFilenames];
}

const dtsFiles = {};
const host = ts.createCompilerHost(tsConfig.options);

const dtsFiles: Record<string, string> = {};

host.writeFile = (fileName, contents) => {
dtsFiles[fileName] = contents;
};
Expand Down Expand Up @@ -171,32 +207,23 @@ export async function dtsCompile({ files, rootDir, outputDir, alias }: DtsCompil
});
}

if (!Object.keys(alias).length) {
// no alias config
return _files.map((file) => ({
...file,
dtsContent: dtsFiles[file.dtsPath],
}));
}

// We use tsc-alias to resolve d.ts alias.
// Reason: https://github.com/microsoft/TypeScript/issues/30952#issuecomment-1114225407
const tsConfigLocalPath = path.join(rootDir, 'node_modules/.cache/ice-pkg/tsconfig.json');
await fse.ensureFile(tsConfigLocalPath);
await fse.writeJSON(tsConfigLocalPath, {
...tsConfig,
compilerOptions: tsConfig.options,
}, { spaces: 2 });
return dtsFiles
}

const runFile = await prepareSingleFileReplaceTscAliasPaths({
configFile: tsConfigLocalPath,
outDir: outputDir,
});
async function compileFromOxc(absFiles: DtsInputFile[], tsConfig: ts.ParsedCommandLine): Promise<Record<string, string>> {
if (!tsConfig.options.isolatedDeclarations) {
consola.warn(`Enable isolatedDeclarations in tsconfig.json for correct .d.ts file generation`)

Check failure on line 215 in packages/pkg/src/helpers/dts.ts

View workflow job for this annotation

GitHub Actions / CI (18)

Strings must use singlequote
}
const oxc = await import('oxc-transform');
const dtsFiles: Record<string, string> = {};
for (const file of absFiles) {
const fileContent = fse.readFileSync(file.filePath, 'utf-8');
const { code } = oxc.isolatedDeclaration(file.filePath, fileContent, {
sourcemap: false,
});

const result = _files.map((file) => ({
...file,
dtsContent: dtsFiles[file.dtsPath] ? runFile({ fileContents: dtsFiles[file.dtsPath], filePath: file.dtsPath }) : '',
}));
dtsFiles[file.dtsPath] = code;
}

return result;
return dtsFiles
}
1 change: 1 addition & 0 deletions packages/pkg/src/tasks/declaration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ class DeclarationRunner extends Runner<OutputResult> {
rootDir: context.buildContext.rootDir,
outputDir: buildConfig.outputDir,
alias: buildConfig.alias,
usingOxc: buildConfig.generator === 'oxc',
}]);

await worker.terminate();
Expand Down
8 changes: 8 additions & 0 deletions packages/pkg/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,14 @@ export interface DeclarationUserConfig {
* @default 'multi'
*/
outputMode?: 'multi' | 'unique';

/**
* The generator to generate .d.ts file
* - `'tsc'` use typescript
* - `'oxc'` use oxc-transform to generate isolated declaration
* @default 'tsc'
*/
generator?: 'tsc' | 'oxc';
}

export interface UserConfig {
Expand Down
Loading

0 comments on commit 7a6f343

Please sign in to comment.