Skip to content

Commit

Permalink
Merge branch 'catch-syntax-errors' into combine-prs
Browse files Browse the repository at this point in the history
  • Loading branch information
kulshekhar committed Jun 30, 2018
2 parents 67659c4 + 56c3714 commit 6ff8b2c
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/transpiler.ts
Expand Up @@ -30,8 +30,34 @@ function transpileViaTranspileModule(
fileSource: string,
compilerOptions: ts.CompilerOptions,
): ts.TranspileOutput {
return ts.transpileModule(fileSource, {
const transpileOutput = ts.transpileModule(fileSource, {
compilerOptions,
fileName: filePath,
reportDiagnostics: true,
});
const {diagnostics} = transpileOutput;

if (diagnostics.length > 0) {
const errors = formatDiagnostics(diagnostics);
logOnce(logMessageForTranspilationErrors(errors));
// Maybe we should keep compiling even though there are errors. This can possibly be configured.
throw createTranspilationError(errors);
}

return transpileOutput;
}

function formatDiagnostics(diagnostics: ts.Diagnostic[]): string {
// TODO consider using ts.formatDiagnosticsWithColorAndContext()
return `${diagnostics.map(d => d.messageText)}\n`;
}

function createTranspilationError(errors: string): Error {
return Error(
`TypeScript compiler encountered syntax errors while transpiling. Errors: ${errors}`,
);
}

function logMessageForTranspilationErrors(errors: string): string {
return `Diagnostic errors from TSC: ${errors}`;
}
23 changes: 23 additions & 0 deletions tests/__tests__/transpiler.spec.ts
@@ -0,0 +1,23 @@
import { transpileTypescript } from '../../src/transpiler';
import * as ts from 'typescript';

describe('transpileTypescript', () => {

const compilerOptions: ts.CompilerOptions = {newLine: ts.NewLineKind.LineFeed};

it('should transpile valid TS syntax', () => {
const result = transpileTypescript('valid.ts', 'var a = true;', compilerOptions);
expect(result.code).toBe('var a = true;\n');
});

it('should transpile valid TS syntax with type errors', () => {
const result = transpileTypescript('valid.ts', 'var a: string = true;', compilerOptions);
expect(result.code).toBe('var a = true;\n');
});

it('should throw an error when transpiling invalid TS syntax', () => {
expect(() => {
transpileTypescript('invalid.ts', 'var a = ;', compilerOptions);
}).toThrow('TypeScript compiler encountered syntax errors while transpiling. Errors: Expression expected.');
});
});

0 comments on commit 6ff8b2c

Please sign in to comment.