Skip to content
This repository has been archived by the owner on Oct 18, 2023. It is now read-only.

Commit

Permalink
fix(typescript): resolve js to ts (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
privatenumber committed May 25, 2022
1 parent 3696ed5 commit d14ca36
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 15 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"test": "node --loader @esbuild-kit/esm-loader tests"
},
"dependencies": {
"@esbuild-kit/core-utils": "^1.1.2",
"@esbuild-kit/core-utils": "^1.2.0",
"es-module-lexer": "^0.10.5",
"get-tsconfig": "^3.0.1"
},
Expand Down
8 changes: 4 additions & 4 deletions pnpm-lock.yaml

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

22 changes: 12 additions & 10 deletions src/loaders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
transform,
installSourceMapSupport,
transformDynamicImport,
resolveTsPath,
} from '@esbuild-kit/core-utils';
import getTsconfig from 'get-tsconfig';
import {
Expand Down Expand Up @@ -56,17 +57,18 @@ export const resolve: resolve = async function (
}

/**
* Typescript gives .mts or .cts priority over actual .mjs or .cjs extensions
* Typescript gives .ts, .cts, or .mts priority over actual .js, .cjs, or .mjs extensions
*/
if (
/\.[cm]js$/.test(specifier)
&& tsExtensionsPattern.test(context.parentURL!)
) {
try {
return await resolve(`${specifier.slice(0, -2)}ts`, context, defaultResolve);
} catch (error) {
if ((error as any).code !== 'ERR_MODULE_NOT_FOUND') {
throw error;
if (tsExtensionsPattern.test(context.parentURL!)) {
const tsPath = resolveTsPath(specifier);

if (tsPath) {
try {
return await resolve(tsPath, context, defaultResolve);
} catch (error) {
if ((error as any).code !== 'ERR_MODULE_NOT_FOUND') {
throw error;
}
}
}
}
Expand Down
14 changes: 14 additions & 0 deletions tests/specs/typescript/ts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,20 @@ export default testSuite(async ({ describe }, node: NodeApis) => {
});
});

describe('full path via .js', ({ test }) => {
const importPath = './lib/ts-ext-ts/index.js';

test('Load - should not work', async () => {
const nodeProcess = await node.load(importPath);
expect(nodeProcess.stderr).toMatch('Cannot find module');
});

test('Import', async () => {
const nodeProcess = await node.import(importPath, { typescript: true });
expect(nodeProcess.stdout).toBe(`${output}\n{"default":1234}`);
});
});

describe('extensionless', ({ test }) => {
const importPath = './lib/ts-ext-ts/index';

Expand Down

0 comments on commit d14ca36

Please sign in to comment.