File size: 1,071 Bytes
95f4e64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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,
            };
        });
    },
});