Skip to content

Commit

Permalink
Add support of ts5+
Browse files Browse the repository at this point in the history
  • Loading branch information
ZettZet committed Nov 14, 2023
1 parent ce8c5e8 commit 1f60be5
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 3 deletions.
16 changes: 15 additions & 1 deletion test/compile/compile.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,26 @@
import ts from 'typescript';
import transformer from '../../transformer';

function getDefaultModuleResolution(): ts.ModuleResolutionKind {
if('NodeJs' in ts.ModuleResolutionKind) {
return ts.ModuleResolutionKind.NodeJs;
}

if('Node10' in ts.ModuleResolutionKind) {
// @ts-ignore forward compatibility check
return ts.ModuleResolutionKind.Node10 as ts.ModuleResolutionKind;
}

throw new Error('Cannot choose default module resolution kind')
}

export function compile(filePaths: string[], target = ts.ScriptTarget.ES5, writeFileCallback?: ts.WriteFileCallback) {
const program = ts.createProgram(filePaths, {
strict: true,
noEmitOnError: true,
suppressImplicitAnyIndexErrors: true,
noUncheckedIndexedAccess: false,
esModuleInterop: true,
moduleResolution: getDefaultModuleResolution(),
target
});
const transformers: ts.CustomTransformers = {
Expand Down
35 changes: 33 additions & 2 deletions transformer.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,39 @@
import ts from 'typescript';
import path from 'path';

const createArrayExpression = ts.factory ? ts.factory.createArrayLiteralExpression : ts.createArrayLiteral;
const createStringLiteral = ts.factory ? ts.factory.createStringLiteral : ts.createLiteral;
type ArrayFactory = (
elements?: readonly ts.Expression[] | undefined,
multiLine?: boolean | undefined
) => ts.ArrayLiteralExpression;

const createArrayExpression = ((): ArrayFactory => {
if (ts.factory) {
return ts.factory.createArrayLiteralExpression;
}

if ("createArrayLiteral" in ts) {
return ts.createArrayLiteral as ArrayFactory;
}

throw new Error("Cannot choose array literal factory");
})();

type StringFactory = (
text: string,
isSingleQuote?: boolean | undefined
) => ts.StringLiteral;

const createStringLiteral = ((): StringFactory => {
if (ts.factory) {
return ts.factory.createStringLiteral;
}

if ("createLiteral" in ts) {
return ts.createLiteral as StringFactory;
}

throw new Error("Cannot choose string literal factory");
})();

export default function transformer(program: ts.Program): ts.TransformerFactory<ts.SourceFile> {
return (context: ts.TransformationContext) => (file: ts.SourceFile) => visitNodeAndChildren(file, program, context);
Expand Down

0 comments on commit 1f60be5

Please sign in to comment.