Skip to content
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 14 additions & 32 deletions packages/rspack/src/util/require.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,40 +23,22 @@ export function nonWebpackRequire(): RequireFn {
return;
}

// Only custom esm loader is supported.
const loaderCode = data?.toString() || "";

// 1. Assume it's a cjs
const codeUrl = URL.createObjectURL(
new Blob([loaderCode], { type: "text/javascript" })
);
try {
// Use `new Function` to emulate CJS
const module = { exports: {} };
const exports = module.exports;
const createRequire = () => {
throw new Error(
"@rspack/browser doesn't support `require` in loaders yet"
);
};

// rslint-disable no-implied-eval
const wrapper = new Function(
"module",
"exports",
"require",
loaderCode
);

wrapper(module, exports, createRequire);
resolve(module.exports);
} catch {
// 2. Assume it's an esm
// Use `import(base64code)` to load ESM
const dataUrl = `data:text/javascript;base64,${btoa(loaderCode)}`;
try {
// biome-ignore lint/security/noGlobalEval: use `eval("import")` rather than `import` to suppress the warning in @rspack/browser
const modulePromise = eval(`import("${dataUrl}")`);
modulePromise.then(resolve);
} catch (e) {
reject(e);
}
// biome-ignore lint/security/noGlobalEval: use `eval("import")` rather than `import` to suppress the warning in @rspack/browser
const modulePromise = eval(
`import("${codeUrl}")`
) as Promise<unknown>;
modulePromise.then(module => {
URL.revokeObjectURL(codeUrl);
resolve(module);
});
} catch (e) {
reject(e);
}
});
})
Expand Down
Loading