Skip to content

Commit

Permalink
feat: support node built-in module
Browse files Browse the repository at this point in the history
  • Loading branch information
sxzz committed Apr 17, 2024
1 parent 00f11d8 commit 43c67e1
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/core/index.ts
@@ -1,3 +1,4 @@
import { builtinModules } from 'node:module'
import {
type ImportBinding,
type WithScope,
Expand Down Expand Up @@ -99,8 +100,16 @@ export async function transformMacros({
const binding = imports.get(local)!
const [, resolved] = await runner.resolveUrl(binding.source, id)

const module = await runner.executeFile(resolved)
let exported: any = module
let exported
if (
resolved.startsWith('node:') ||
builtinModules.includes(resolved.split('/')[0])
) {
exported = await import(resolved)
} else {
const module = await runner.executeFile(resolved)
exported = module
}

const props = [...keys]
if (binding.imported !== '*') props.unshift(binding.imported)
Expand Down
8 changes: 8 additions & 0 deletions tests/__snapshots__/fixtures.test.ts.snap
Expand Up @@ -47,6 +47,14 @@ exports[`fixture > tests/fixtures/nested-object.js 1`] = `
"
`;

exports[`fixture > tests/fixtures/node-builtin.js 1`] = `
""LE" === 'LE'
;("* text=auto eol=lf\\n") ===
// prettier-ignore
"* text=auto eol=lf\\n";
"
`;

exports[`fixture > tests/fixtures/non-macros.js 1`] = `
"function getRandom() {
return Math.random()
Expand Down
7 changes: 7 additions & 0 deletions tests/fixtures/node-builtin.js
@@ -0,0 +1,7 @@
import { endianness } from 'node:os' with { type: 'macro' }
import { readFile } from 'fs/promises' with { type: 'macro' }

endianness() === 'LE'
;(await readFile('.gitattributes', { encoding: 'utf8' })) ===
// prettier-ignore
"* text=auto eol=lf\n"

0 comments on commit 43c67e1

Please sign in to comment.