Skip to content

Commit

Permalink
feat: add oxc-transoform as experimental declaration compiler
Browse files Browse the repository at this point in the history
  • Loading branch information
XGHeaven committed Sep 17, 2024
1 parent 03c6838 commit 92a5f42
Show file tree
Hide file tree
Showing 9 changed files with 217 additions and 49 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-transoform as experimental declaration compiler
3 changes: 2 additions & 1 deletion packages/pkg/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
"gzip-size": "^7.0.0",
"lodash.merge": "^4.6.2",
"magic-string": "^0.25.7",
"oxc-transform": "^0.28.0",
"picocolors": "^1.0.0",
"postcss": "^8.4.6",
"postcss-plugin-rpx2vw": "^1.0.0",
Expand All @@ -67,7 +68,7 @@
"rollup-plugin-visualizer": "^5.8.3",
"semver": "^7.0.0",
"tsc-alias": "^1.8.2",
"typescript": "^4.9.4"
"typescript": "^5.5.0"
},
"devDependencies": {
"@types/babel__core": "^7.1.20",
Expand Down
131 changes: 87 additions & 44 deletions packages/pkg/src/helpers/dts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { prepareSingleFileReplaceTscAliasPaths } from 'tsc-alias';
import fse from 'fs-extra';
import * as path from 'path';
import merge from 'lodash.merge';
import oxc from 'oxc-transform';

export type FileExt = 'js' | 'ts' | 'tsx' | 'jsx' | 'cjs' | 'mjs' | 'mts' | 'cts';

Expand Down Expand Up @@ -45,16 +46,77 @@ interface DtsCompileOptions {
alias: TaskConfig['alias'];
rootDir: string;
outputDir: string;

usingOxc: boolean;
}

export async function dtsCompile({ files, alias, rootDir, outputDir }: DtsCompileOptions): Promise<DtsInputFile[]> {
if (!files.length) {
export async function dtsCompile(options: DtsCompileOptions): Promise<DtsInputFile[]> {
if (!options.files.length) {
return;
}

const tsConfig = await getTSConfig(rootDir, outputDir, alias);
const tsConfig = await getTSConfig(options.rootDir, options.outputDir, options.alias);
const logger = createLogger('dts');

if (options.usingOxc) {
if (!tsConfig.options.isolatedDeclarations) {
logger.warn('[experimental.enableOxcIsolatedDeclaration] prefer to enable isolatedDeclaration in tsconfig.json');
}
if (Object.keys(tsConfig.options.paths ?? {}).length !== 0) {
logger.warn('[experimental.enableOxcIsolatedDeclaration] not works with alias');
}
return compileFromOxc(options);
}

return compileFromTsc(options, tsConfig);
}

async function getTSConfig(
rootDir: string,
outputDir: string,
alias: TaskConfig['alias'],
) {
const defaultTSCompilerOptions: ts.CompilerOptions = {
allowJs: true,
declaration: true,
emitDeclarationOnly: true,
incremental: true,
skipLibCheck: true,
paths: formatAliasToTSPathsConfig(alias), // default add alias to paths
};
const projectTSConfig = await getProjectTSConfig(rootDir);
const tsConfig: ts.ParsedCommandLine = merge(
{ options: defaultTSCompilerOptions },
projectTSConfig,
{
options: {
outDir: outputDir,
rootDir: path.join(rootDir, 'src'),
},
},
);

return tsConfig;
}

async function getProjectTSConfig(rootDir: string): Promise<ts.ParsedCommandLine> {
const tsconfigPath = ts.findConfigFile(rootDir, ts.sys.fileExists);
if (tsconfigPath) {
const tsconfigFile = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
return ts.parseJsonConfigFileContent(
tsconfigFile.config,
ts.sys,
path.dirname(tsconfigPath),
);
}

return {
options: {},
fileNames: [],
errors: [],
};
}

async function compileFromTsc({ files, rootDir, outputDir }: DtsCompileOptions, tsConfig: ts.ParsedCommandLine) {
const logger = createLogger('dts');

logger.debug('Start Compiling typescript declarations...');
Expand Down Expand Up @@ -147,48 +209,29 @@ export async function dtsCompile({ files, alias, rootDir, outputDir }: DtsCompil
return result;
}

async function getTSConfig(
rootDir: string,
outputDir: string,
alias: TaskConfig['alias'],
) {
const defaultTSCompilerOptions: ts.CompilerOptions = {
allowJs: true,
declaration: true,
emitDeclarationOnly: true,
incremental: true,
skipLibCheck: true,
paths: formatAliasToTSPathsConfig(alias), // default add alias to paths
};
const projectTSConfig = await getProjectTSConfig(rootDir);
const tsConfig: ts.ParsedCommandLine = merge(
{ options: defaultTSCompilerOptions },
projectTSConfig,
{
options: {
outDir: outputDir,
rootDir: path.join(rootDir, 'src'),
},
},
);
async function compileFromOxc({ files, alias, rootDir, outputDir }: DtsCompileOptions) {
const _files = files
.map((file) => normalizeDtsInput(file, rootDir, outputDir))
.map(({ filePath, dtsPath, ...rest }) => ({
...rest,
// Be compatible with Windows env.
filePath: normalizePath(filePath),
dtsPath: normalizePath(dtsPath),
}));

return tsConfig;
}
const dtsFiles: Record<string, string> = {};
for (const file of _files) {
const fileContent = fse.readFileSync(file.filePath, 'utf-8');
const { code, map } = oxc.isolatedDeclaration(file.filePath, fileContent, {
sourcemap: true,
});

async function getProjectTSConfig(rootDir: string): Promise<ts.ParsedCommandLine> {
const tsconfigPath = ts.findConfigFile(rootDir, ts.sys.fileExists);
if (tsconfigPath) {
const tsconfigFile = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
return ts.parseJsonConfigFileContent(
tsconfigFile.config,
ts.sys,
path.dirname(tsconfigPath),
);
dtsFiles[file.filePath] = code;
// fse.writeFileSync(file.dtsPath, code)
}

return {
options: {},
fileNames: [],
errors: [],
};
return _files.map((file) => ({
...file,
dtsContent: dtsFiles[file.filePath],
}));
}
1 change: 1 addition & 0 deletions packages/pkg/src/helpers/getRollupOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ export function getRollupOptions(
generateTypesForJs: userConfig.generateTypesForJs,
alias: taskConfig.alias,
outputDir: taskConfig.outputDir,
usingOxc: !!userConfig.experimental?.enableOxcIsolatedDeclaration,
}),
);
}
Expand Down
4 changes: 3 additions & 1 deletion packages/pkg/src/rollupPlugins/dts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ interface DtsPluginOptions {
entry: Record<string, string>;
alias: TaskConfig['alias'];
outputDir: string;
usingOxc: boolean;
generateTypesForJs?: UserConfig['generateTypesForJs'];
}

Expand All @@ -24,6 +25,7 @@ function dtsPlugin({
alias,
generateTypesForJs,
outputDir,
usingOxc,
}: DtsPluginOptions): Plugin {
const includeFileRegexps = [/\.(?:[cm]?ts|tsx)$/];
if (generateTypesForJs) {
Expand Down Expand Up @@ -67,7 +69,7 @@ function dtsPlugin({
filePath: id,
srcCode: cachedContents[id].srcCode,
}));
dtsFiles = await dtsCompile({ files, alias, rootDir, outputDir });
dtsFiles = await dtsCompile({ files, alias, rootDir, outputDir, usingOxc });
} else {
dtsFiles = Object.keys(cachedContents).map((id) => {
const { updated, ...rest } = cachedContents[id];
Expand Down
13 changes: 13 additions & 0 deletions packages/pkg/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,19 @@ export interface UserConfig {
* "bundle mode" means bundle everything up by using Rollup
*/
bundle?: BundleUserConfig;

/**
* Experimental features
* Is not ready for procution. If you found any bugs, please report to https://github.com/ice-lab/icepkg/issues
*/
experimental?: ExperimentalUserConfig;
}

export interface ExperimentalUserConfig {
/**
* Using oxc-transform to genreation [isolated declaration](https://www.typescriptlang.org/tsconfig/#isolatedDeclarations).
*/
enableOxcIsolatedDeclaration?: boolean;
}

interface _TaskConfig {
Expand Down
2 changes: 1 addition & 1 deletion packages/pkg/tests/projects/default.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,5 +60,5 @@ runProjectTest('default', [
config: {
sourceMaps: true
}
}
},
])
91 changes: 89 additions & 2 deletions pnpm-lock.yaml

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

16 changes: 16 additions & 0 deletions website/docs/reference/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -508,3 +508,19 @@ export default defineConfig({
- index.esm.es2017.development.js # 输出未压缩产物 (ES module + es2017)
- index.esm.es2017.production.js # 输出未压缩产物 (ES module + es2017)
```

### experimental

实验性参数,如果遇到问题,请提交到[此处](https://github.com/ice-lab/icepkg/issues)

#### enableOxcIsolatedDeclaration

+ 类型:`boolean`
+ 可用版本:`1.6.0`

使用 `oxc-transform` 替代 `tsc` 去生成 [isolated declaration](https://www.typescriptlang.org/tsconfig/#isolatedDeclarations),可以获得数十倍的构建性能提升。

开启此选项需要注意以下内容:

- `isolated declaration` 是 TypeScript 5.5 引入的新功能,需要开启此功能,请保证你的代码对此兼容
- `oxc-transform` 目前不支持 alias 能力

0 comments on commit 92a5f42

Please sign in to comment.