From 57786185c8bc10742b9e891e8a6126c51660f1f9 Mon Sep 17 00:00:00 2001 From: Maximilian Fellner Date: Wed, 7 Nov 2018 21:34:39 +0100 Subject: [PATCH] feat: use esModuleInterop when defined (fixes #179) (#61) --- src/ts-node.ts | 2 ++ test/ts-node.test.ts | 70 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 test/ts-node.test.ts diff --git a/src/ts-node.ts b/src/ts-node.ts index 64570cde..59ca1aa0 100644 --- a/src/ts-node.ts +++ b/src/ts-node.ts @@ -17,6 +17,7 @@ export interface TSConfig { rootDirs?: string[] outDir?: string target?: string + esModuleInterop?: boolean; } } @@ -43,6 +44,7 @@ function registerTSNode(root: string) { // cache: false, // typeCheck: true, compilerOptions: { + esModuleInterop: tsconfig.compilerOptions.esModuleInterop, target: tsconfig.compilerOptions.target || 'es2017', module: 'commonjs', sourceMap: true, diff --git a/test/ts-node.test.ts b/test/ts-node.test.ts new file mode 100644 index 00000000..15d16f3b --- /dev/null +++ b/test/ts-node.test.ts @@ -0,0 +1,70 @@ +import * as path from 'path' +import * as tsNode from 'ts-node' + +import {TSConfig} from '../src/ts-node' +import * as util from '../src/util' + +import {expect, fancy} from './test' + +const root = path.resolve(__dirname, 'fixtures/typescript') +const orig = 'src/hooks/init.ts' +let tsNodeRegisterCallArguments: any[] = [] + +/** + * Delete a module from the require cache before requiring it. + */ +export default function freshRequire(name: string) { + delete require.cache[require.resolve(name)] + return require(name) +} + +const DEFAULT_TS_CONFIG: TSConfig = { + compilerOptions: {} +} + +const withMockTsConfig = (config: TSConfig = DEFAULT_TS_CONFIG) => + fancy + .stub(tsNode, 'register', (arg: any) => { + tsNodeRegisterCallArguments.push(arg) + }) + .stub(util, 'loadJSONSync', (arg: string) => { + if (arg.endsWith('tsconfig.json')) { + return config + } + }) + .finally(() => { + tsNodeRegisterCallArguments = [] + }) + +describe('tsPath', () => { + withMockTsConfig() + .it('should resolve a .ts file', () => { + const {tsPath} = freshRequire('../src/ts-node') + const result = tsPath(root, orig) + expect(result).to.equal(path.join(root, orig)) + }) + + withMockTsConfig() + .it('should leave esModuleInterop undefined by default', () => { + const {tsPath} = freshRequire('../src/ts-node') + tsPath(root, orig) + expect(tsNodeRegisterCallArguments.length).is.equal(1) + expect(tsNodeRegisterCallArguments[0]) + .to.have.nested.property('compilerOptions.esModuleInterop') + .equal(undefined) + }) + + withMockTsConfig({ + compilerOptions: { + esModuleInterop: true + } + }) + .it('should use the provided esModuleInterop option', () => { + const {tsPath} = freshRequire('../src/ts-node') + tsPath(root, orig) + expect(tsNodeRegisterCallArguments.length).is.equal(1) + expect(tsNodeRegisterCallArguments[0]) + .to.have.nested.property('compilerOptions.esModuleInterop') + .equal(true) + }) +})