Skip to content
Merged
Changes from all 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
49 changes: 17 additions & 32 deletions packages/rspack/src/util/require.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,40 +23,25 @@ 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);
}
// We have to use `eval` to prevent this dynamic import being handled by any bundler.
// Applications should config their CSP to allow `unsafe-eval`.
// In the future, we may find a better way to handle this, such as user-injected module executor.
// 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