Skip to content

Commit

Permalink
Merge pull request #9 from inottn/fix/7
Browse files Browse the repository at this point in the history
  • Loading branch information
LingyuCoder authored Oct 11, 2024
2 parents d0be767 + 9706888 commit e3ff091
Showing 1 changed file with 21 additions and 16 deletions.
37 changes: 21 additions & 16 deletions src/alias.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,51 @@
const Module = require("module");
const Module = require("node:module");
const MODULE_MAP: Record<string, typeof Module._resolveFilename> = {};
const RESOLVER_MAP: Record<string, typeof require.resolve> = {};

export const addResolveAlias = (
name: string,
aliasMap: Record<string, string>
aliasMap: Record<string, string>,
) => {
const modulePath = require.resolve(name);
if (RESOLVER_MAP[modulePath]) {
if (modulePath in RESOLVER_MAP) {
throw new Error(`Should not add resolve alias to ${name} again.`);
}
const m = require.cache[modulePath];
if (!m) {
throw new Error("Failed to resolve webpack-dev-server.");
}
RESOLVER_MAP[modulePath] = m.require.resolve;
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
m.require.resolve = ((id: string, options?: any) =>
aliasMap[id] ||
RESOLVER_MAP[modulePath]!.apply(m.require, [
RESOLVER_MAP[modulePath].apply(m.require, [
id,
options
options,
])) as typeof require.resolve;
MODULE_MAP[modulePath] = Module._resolveFilename;
Module._resolveFilename = Module._resolveFilename = (request: string, mod: NodeModule, ...args: unknown[]) => {
if (mod.filename === modulePath && aliasMap[request]) {
return aliasMap[request];
}
return MODULE_MAP[modulePath](request, mod, ...args);
Module._resolveFilename = (
request: string,
mod: NodeModule,
...args: unknown[]
) => {
if (mod.filename === modulePath && aliasMap[request]) {
return aliasMap[request];
}
return MODULE_MAP[modulePath](request, mod, ...args);
};
};

export const removeResolveAlias = (name: string) => {
const modulePath = require.resolve(name);
if (!RESOLVER_MAP[modulePath]) {
if (!(modulePath in RESOLVER_MAP)) {
return;
}
const m = require.cache[modulePath];
if (!m) {
throw new Error("Failed to resolve webpack-dev-server");
}
if (RESOLVER_MAP[modulePath]) {
Module._resolveFilename = RESOLVER_MAP[modulePath]!;
m.require.resolve = RESOLVER_MAP[modulePath]!;
delete RESOLVER_MAP[modulePath];
}

Module._resolveFilename = MODULE_MAP[modulePath];
m.require.resolve = RESOLVER_MAP[modulePath];
delete RESOLVER_MAP[modulePath];
};

0 comments on commit e3ff091

Please sign in to comment.