Skip to content

Commit

Permalink
fix(tsImport): handle importing packages (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
privatenumber authored May 4, 2024
1 parent 63631ac commit 96bc596
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 24 deletions.
51 changes: 29 additions & 22 deletions src/esm/hook/resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,35 @@ export const resolve: resolve = async (
return nextResolve(specifier, context);
}

const isPath = (
specifier.startsWith(fileProtocol)
|| isRelativePathPattern.test(specifier)
);

// bare specifier
if (!isPath) {
// TS path alias
if (
tsconfigPathsMatcher
&& !context.parentURL?.includes('/node_modules/')
) {
const possiblePaths = tsconfigPathsMatcher(specifier);
for (const possiblePath of possiblePaths) {
try {
return await resolve(
pathToFileURL(possiblePath).toString(),
context,
nextResolve,
);
} catch {}
}
}

// npm package -- use default resolution
return nextResolve(specifier, context);
}

// Inherit namespace from parent
let requestNamespace = getNamespace(specifier);
if (context.parentURL) {
const parentNamespace = getNamespace(context.parentURL);
Expand All @@ -139,28 +168,6 @@ export const resolve: resolve = async (
return await tryDirectory(specifier, context, nextResolve);
}

const isPath = (
specifier.startsWith(fileProtocol)
|| isRelativePathPattern.test(specifier)
);

if (
tsconfigPathsMatcher
&& !isPath // bare specifier
&& !context.parentURL?.includes('/node_modules/')
) {
const possiblePaths = tsconfigPathsMatcher(specifier);
for (const possiblePath of possiblePaths) {
try {
return await resolve(
pathToFileURL(possiblePath).toString(),
context,
nextResolve,
);
} catch {}
}
}

// Typescript gives .ts, .cts, or .mts priority over actual .js, .cjs, or .mjs extensions
//
// If `allowJs` is set in `tsconfig.json`, then we'll apply the same resolution logic
Expand Down
12 changes: 10 additions & 2 deletions tests/specs/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,15 @@ const tsFiles = {
import { bar } from './bar.js'
export const foo = \`foo \${bar}\` as string
`,
'bar.ts': 'export const bar = "bar" as string',
'bar.ts': 'export type A = 1; export { bar } from "pkg"',
'node_modules/pkg': {
'package.json': JSON.stringify({
name: 'pkg',
type: 'module',
exports: './index.js',
}),
'index.js': 'export const bar = "bar"',
},
};

export default testSuite(({ describe }, node: NodeApis) => {
Expand Down Expand Up @@ -244,7 +252,7 @@ export default testSuite(({ describe }, node: NodeApis) => {
nodePath: node.path,
nodeOptions: [],
});
expect(stdout).toBe('file.ts\nfoo.ts\nbar.ts');
expect(stdout).toBe('file.ts\nfoo.ts\nbar.ts\nindex.js');
});
});

Expand Down

0 comments on commit 96bc596

Please sign in to comment.