Last active
April 27, 2023 19:36
-
-
Save isaacs/e4386a50b43575582e839918850d045d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Hello from foo! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With this approach,
node --loader=./loader.mjs foo.foo
andnode -r ./exts.cjs foo.foo
both work