Skip to content

Commit

Permalink
re-resolve on relative js
Browse files Browse the repository at this point in the history
  • Loading branch information
calebboyd committed Jun 6, 2021
1 parent ae98597 commit eb30ac3
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 5 deletions.
33 changes: 28 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { BaseError } from 'make-error';
import type * as _ts from 'typescript';

import type { Transpiler, TranspilerFactory } from './transpilers/types';
import { assign, normalizeSlashes, parse, split, yn } from './util';
import { assign, normalizeSlashes, parse, split, yn, isRelativeSpecifier } from './util';
import { readConfig } from './configuration';
import type { TSCommon, TSInternal } from './ts-compiler-types';

Expand Down Expand Up @@ -411,17 +411,40 @@ export function getExtensions(config: _ts.ParsedCommandLine) {
return { tsExtensions, jsExtensions };
}

function canDropJsExt(request: string, parentPath?: string) {
if (isRelativeSpecifier(request) && request.slice(-3) === '.js') {
if (!parentPath) return true
const paths = require.main?.paths || []
for(let i = 0; i < paths.length; i++) {
if (parentPath.startsWith(paths[i])) {
return false
}
}
return true
}
}


function patchResolveFileName() {
const originalResolveFilename = (Module as any)._resolveFilename;
const jsExt = '.js';

(Module as any)._resolveFilename = function (...args: any[]) {
const [request, _, isMain ] = args
const [request, parent, isMain ] = args
if (isMain) {
return originalResolveFilename.apply(this, args);
}
if(request.slice(-3) === jsExt) {
args[0] = request.slice(0, -3)
if(canDropJsExt(request, parent?.path)) {
try {
return originalResolveFilename.call(this, request.slice(0, -3), ...args.slice(1))
} catch(e) {
const mainFile = originalResolveFilename.apply(this, args);
if (mainFile.endsWith('.js')) {
//re-resolve with ts preference
//look-up tsconfig drop outDir??
return originalResolveFilename.call(this, mainFile.slice(0, -3), ...args.slice(1))
}
return mainFile
}
}
return originalResolveFilename.apply(this, args);
};
Expand Down
15 changes: 15 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,18 @@ export function parse(value: string | undefined): object | undefined {
export function normalizeSlashes(value: string): string {
return value.replace(/\\/g, '/');
}

/**
*
* Determine if a specifier is relative (from node core)
* @internal
*/
export function isRelativeSpecifier(specifier: string) {
if (specifier[0] === '.') {
if (specifier.length === 1 || specifier[1] === '/') return true;
if (specifier[1] === '.') {
if (specifier.length === 2 || specifier[2] === '/') return true;
}
}
return false;
}

0 comments on commit eb30ac3

Please sign in to comment.