UNPKG

@digitak/esrun

Version:

Execute directly your Typescript files using Esbuild

25 lines (24 loc) 1.07 kB
import { posix } from "path"; import process from "process"; import fs from "fs"; import { grub } from "@digitak/grubber"; export const fileConstantsPlugin = (options = {}) => ({ name: "fileConstants", setup(build) { build.onLoad({ filter: /.\.(c|m)?(js|ts)x?$/, namespace: "file" }, async (options) => { const isWindows = /^win/.test(process.platform); const escapeBackslashes = (path) => isWindows ? path.replace(/\\/g, "/") : path; const filename = escapeBackslashes(options.path); const dirname = posix.dirname(options.path); const fileContent = fs.readFileSync(options.path, "utf8"); const contents = grub(fileContent).replace({ from: "__dirname", to: `"${dirname}"` }, { from: "__filename", to: `"${filename}"` }); let loader = posix.extname(options.path).slice(1); if (["m", "c"].includes(loader[0])) loader = loader.slice(1); return { contents, loader, }; }); }, });