Skip to content

Instantly share code, notes, and snippets.

@isaacs
Last active April 27, 2023 19:36
Show Gist options
  • Save isaacs/e4386a50b43575582e839918850d045d to your computer and use it in GitHub Desktop.
Save isaacs/e4386a50b43575582e839918850d045d to your computer and use it in GitHub Desktop.
console.error('register extension', process.version)
const { writeFileSync, readFileSync } = require('fs')
const transpile = exports.transpile = file => {
const src = readFileSync(file, 'utf8')
const tx = `console.log(${JSON.stringify(src)})`
writeFileSync(file + '.cjs', tx)
}
require.extensions['.foo'] = (module, file) => {
transpile(file)
module.filename = file + '.cjs'
return require.extensions['.js'](module, file + '.cjs')
}
Hello from foo!
import { createRequire } from 'node:module'
import {fileURLToPath} from 'node:url'
const require = createRequire(import.meta.url)
const { transpile } = require('./exts.cjs')
export const load = (url, context, defaultLoad) =>{
console.error('load', url, context, defaultLoad)
if (url.endsWith('.foo')) {
transpile(fileURLToPath(url))
url += '.cjs'
}
return defaultLoad(url, context)
}
@isaacs
Copy link
Author

isaacs commented Apr 27, 2023

With this approach, node --loader=./loader.mjs foo.foo and node -r ./exts.cjs foo.foo both work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment