Skip to content
This repository was archived by the owner on May 12, 2022. It is now read-only.

Commit 12c8733

Browse files
authored
feat: support tsconfig-paths (#21)
1 parent e240bd0 commit 12c8733

File tree

9 files changed

+89
-18
lines changed

9 files changed

+89
-18
lines changed

loader.mjs

Lines changed: 39 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,20 @@
11
import { URL, pathToFileURL, fileURLToPath } from 'url'
22
import fs from 'fs'
33
import { transformSync } from 'esbuild'
4+
import { createMatchPath, loadConfig } from 'tsconfig-paths'
45

56
const baseURL = pathToFileURL(`${process.cwd()}/`).href
67
const isWindows = process.platform === 'win32'
78

8-
const extensionsRegex = /\.(tsx?|json)$/
9+
const extensionsRegex = /\.(m?tsx?|json)$/
910
const excludeRegex = /^\w+:/
11+
const tsExtensions = ['.mts', '.ts', '.cts', '.tsx'] // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-5.html
12+
const jsExtensions = ['.mjs', '.js', '.cjs', '.jsx']
13+
const extensions = [...tsExtensions, ...jsExtensions]
14+
15+
const tsconfig = loadConfig()
16+
17+
const matchPath = tsconfig.resultType === 'success' ? createMatchPath(tsconfig.absoluteBaseUrl, tsconfig.paths) : undefined
1018

1119
function esbuildTransformSync(rawSource, filename, url, format) {
1220
const {
@@ -31,7 +39,29 @@ function esbuildTransformSync(rawSource, filename, url, format) {
3139
return { js, jsSourceMap }
3240
}
3341

42+
export const tryPathWithExtensions = (path) => {
43+
for (const ext of extensions) {
44+
const p = `${path}${ext}`
45+
if (fs.existsSync(p))
46+
return p
47+
}
48+
return null
49+
}
50+
3451
export function resolve(specifier, context, defaultResolve) {
52+
// baseUrl & paths takes the highest precedence, as TypeScript behaves.
53+
if (matchPath) {
54+
const nodePath = matchPath(specifier, undefined, undefined, extensions)
55+
56+
if (nodePath) {
57+
const foundPath = tryPathWithExtensions(nodePath)
58+
return {
59+
url: pathToFileURL(foundPath).href,
60+
format: extensionsRegex.test(foundPath) && 'module',
61+
}
62+
}
63+
}
64+
3565
const { parentURL = baseURL } = context
3666
const url = new URL(specifier, parentURL)
3767
if (extensionsRegex.test(url.pathname))
@@ -40,15 +70,14 @@ export function resolve(specifier, context, defaultResolve) {
4070
// ignore `data:` and `node:` prefix etc.
4171
if (!excludeRegex.test(specifier)) {
4272
// Try to resolve extension
43-
const pathname = url.pathname
44-
for (const ext of ['ts', 'tsx']) {
45-
url.pathname = `${pathname}.${ext}`
46-
const path = fileURLToPath(url.href)
47-
if (fs.existsSync(path))
48-
return {
49-
url: url.href,
50-
format: extensionsRegex.test(url.pathname) && 'module',
51-
}
73+
const path = fileURLToPath(url.href)
74+
const foundPath = tryPathWithExtensions(path)
75+
if (foundPath) {
76+
url.pathname = foundPath
77+
return {
78+
url: url.href,
79+
format: extensionsRegex.test(url.pathname) && 'module',
80+
}
5281
}
5382
}
5483

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@
3333
"test": "node --experimental-loader ./loader.mjs test/entry.ts"
3434
},
3535
"dependencies": {
36-
"esbuild": "^0.13.3"
36+
"esbuild": "^0.13.3",
37+
"tsconfig-paths": "^3.11.0"
3738
},
3839
"devDependencies": {
3940
"@antfu/eslint-config": "^0.9.0",

pnpm-lock.yaml

Lines changed: 2 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

test/entry.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ import { test } from 'uvu'
44
import execa from 'execa'
55

66
const cwd = process.cwd()
7-
function relativize(path: string) {
8-
return `./${relative(cwd, path)}`
7+
function relativize(path: string, curCwd = cwd) {
8+
return `./${relative(curCwd, path)}`
99
}
1010

1111
test('register', async() => {
@@ -107,4 +107,16 @@ test('import json', async() => {
107107
assert(stdout === 'esbuild-node-loader')
108108
})
109109

110+
test('tsconfig-paths', async() => {
111+
const cwd2 = `${cwd}/test/tsconfig-paths`;
112+
const { stdout } = await execa('node', [
113+
'--experimental-loader',
114+
relativize(`${cwd}/loader.mjs`, cwd2),
115+
relativize(`${cwd}/test/tsconfig-paths/src/utils/fixture.ts`, cwd2),
116+
], {
117+
cwd: cwd2,
118+
})
119+
assert.equal(stdout, 'foo\nfoo')
120+
})
121+
110122
test.run()

test/tsconfig-paths/node_modules/@apis/foo.ts

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

test/tsconfig-paths/src/apis/foo.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export const foo = () => {
2+
console.info('foo')
3+
}

test/tsconfig-paths/src/apis/index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export const index = () => {
2+
console.info('index')
3+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { foo as foo2 } from 'src/apis/foo'
2+
import { foo } from '@apis/foo'
3+
4+
foo()
5+
foo2()

test/tsconfig-paths/tsconfig.json

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
"compilerOptions": {
3+
"target": "esnext",
4+
"module": "esnext", /* Allow JavaScript files to be a part o
5+
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
6+
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
7+
8+
/* Type Checking */
9+
"strict": true,
10+
"skipLibCheck": true, /* Skip type checking all .d.ts files. */
11+
"noEmit": true,
12+
"baseUrl": ".",
13+
"paths": {
14+
"@apis/*": ["src/apis/*"],
15+
"@utils/*": ["src/utils/*"]
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)