31 lines
779 B
TypeScript
31 lines
779 B
TypeScript
import { basename, dirname } from "path"
|
|
import type { BabelPlugin } from "./esbuild-babel"
|
|
|
|
export const fileName =
|
|
({
|
|
hasFileName,
|
|
hasDirName,
|
|
path,
|
|
}: {
|
|
hasFileName: boolean
|
|
hasDirName: boolean
|
|
path: string
|
|
}): BabelPlugin =>
|
|
({ types: t }) => ({
|
|
name: "__filename polyfill",
|
|
visitor: {
|
|
Program(program) {
|
|
const assign = (id: string, value: string) =>
|
|
t.variableDeclaration("var", [
|
|
t.variableDeclarator(t.identifier(id), t.stringLiteral(value)),
|
|
])
|
|
if (hasFileName) {
|
|
program.node.body.unshift(assign("__filename", basename(path)))
|
|
}
|
|
if (hasDirName) {
|
|
program.node.body.unshift(assign("__dirname", dirname(path)))
|
|
}
|
|
},
|
|
},
|
|
})
|