Skip to content

Commit e5fe1c1

Browse files
authored
fix: don't treat .node.js as native node module, closes #589
1 parent 095b8ca commit e5fe1c1

File tree

2 files changed

+39
-11
lines changed

2 files changed

+39
-11
lines changed

src/esbuild/native-node-module.ts

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import path from 'path'
12
import { Plugin } from 'esbuild'
23

34
// Copied from https://github.com/evanw/esbuild/issues/1051#issuecomment-806325487
@@ -7,20 +8,34 @@ export const nativeNodeModulesPlugin = (): Plugin => {
78
setup(build) {
89
// If a ".node" file is imported within a module in the "file" namespace, resolve
910
// it to an absolute path and put it into the "node-file" virtual namespace.
10-
build.onResolve({ filter: /\.node$/, namespace: 'file' }, (args) => ({
11-
path: require.resolve(args.path, { paths: [args.resolveDir] }),
12-
namespace: 'node-file',
13-
}))
11+
build.onResolve({ filter: /\.node$/, namespace: 'file' }, (args) => {
12+
const resolvedId = require.resolve(args.path, {
13+
paths: [args.resolveDir],
14+
})
15+
if (resolvedId.endsWith('.node')) {
16+
return {
17+
path: resolvedId,
18+
namespace: 'node-file',
19+
}
20+
}
21+
return {
22+
path: resolvedId,
23+
}
24+
})
1425

1526
// Files in the "node-file" virtual namespace call "require()" on the
1627
// path from esbuild of the ".node" file in the output directory.
17-
build.onLoad({ filter: /.*/, namespace: 'node-file' }, (args) => ({
18-
contents: `
19-
import path from ${JSON.stringify(args.path)}
20-
try { module.exports = require(path) }
21-
catch {}
22-
`,
23-
}))
28+
build.onLoad({ filter: /.*/, namespace: 'node-file' }, (args) => {
29+
console.log(args.path)
30+
return {
31+
contents: `
32+
import path from ${JSON.stringify(args.path)}
33+
try { module.exports = require(path) }
34+
catch {}
35+
`,
36+
resolveDir: path.dirname(args.path),
37+
}
38+
})
2439

2540
// If a ".node" file is imported within a module in the "node-file" namespace, put
2641
// it in the "file" namespace where esbuild's default loading behavior will handle

test/index.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -806,3 +806,16 @@ test('dts only: ignore files', async () => {
806806
]
807807
`)
808808
})
809+
810+
test('native-node-module plugin should handle *.node(.js) import properly', async () => {
811+
await run(
812+
getTestName(),
813+
{
814+
'input.tsx': `export * from './hi.node'`,
815+
'hi.node.js': `export const hi = 'hi'`,
816+
},
817+
{
818+
entry: ['input.tsx'],
819+
}
820+
)
821+
})

0 commit comments

Comments
 (0)