Add support for "browser" condition (e.g., as used by Webpack) by stubbing-away Node imports (fixes #1441).

This commit is contained in:
David Anson 2024-12-08 21:04:32 -08:00
parent 65eeb4c8d9
commit a009407088
6 changed files with 45 additions and 32 deletions

View file

@ -1,10 +1,8 @@
// @ts-check
import * as nodeFs from "node:fs";
import { createRequire } from "node:module";
const dynamicRequire = createRequire(import.meta.url);
import * as os from "node:os";
import path from "node:path";
// @ts-ignore
import { fs as nodeFs, module, os, path } from "#node-imports";
const dynamicRequire = module.createRequire(import.meta.url);
import { initialize as cacheInitialize } from "./cache.mjs";
import { version } from "./constants.mjs";
import rules from "./rules.mjs";

View file

@ -0,0 +1,7 @@
// @ts-check
"use strict";
module.exports = {
"createRequire": () => require
};

View file

@ -0,0 +1,22 @@
// @ts-check
const getError = () => new Error("Node APIs are not available in browser context.");
const throwForSync = () => {
throw getError();
};
export const fs = {
"access": (path, callback) => callback(getError()),
"accessSync": throwForSync,
"readFile": (path, options, callback) => callback(getError()),
"readFileSync": throwForSync
};
export { default as module } from "./node-imports-browser-module.cjs";
export const os = {};
export const path = {
"dirname": throwForSync,
"resolve": throwForSync
};

14
lib/node-imports-node.mjs Normal file
View file

@ -0,0 +1,14 @@
// @ts-check
import { access, accessSync, readFile, readFileSync } from "node:fs";
export const fs = { access, accessSync, readFile, readFileSync };
import { createRequire } from "node:module";
export const module = { createRequire };
import { EOL, homedir } from "node:os";
export const os = { EOL, homedir };
// eslint-disable-next-line unicorn/import-style
import { dirname, resolve } from "node:path";
export const path = { dirname, resolve };