From bd8b89ca0692a788efa4654cd1bc236b95e9e451 Mon Sep 17 00:00:00 2001 From: rockofox Date: Sun, 21 Jan 2024 02:42:55 +0100 Subject: [PATCH] feat: allow multiple lines of hashbangs (#715) --- src/cli.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/cli.ts b/src/cli.ts index 54041a1922..58f490ac56 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -179,7 +179,20 @@ async function importPath(filepath: string, origin = filepath) { const __filename = resolve(origin) const __dirname = dirname(__filename) const require = createRequire(origin) + const shebangRegex = /^#!(.*)*\n/ + const file = await fs.readFile(filepath) + Object.assign(global, { __filename, __dirname, require }) + + if (shebangRegex.test(file.toString())) { + return writeAndImport( + await file.toString().replace(shebangRegex, ''), + join(dirname(filepath), basename(filepath) + '.mjs'), + origin + ) + } + + await import(url.pathToFileURL(filepath).toString()) }