Skip to content

Commit 95ba587

Browse files
authored
fix(wasm): remove cjs loader support (#11283)
* Remove cjs loader * Typo * use blob url * add comments
1 parent d406a66 commit 95ba587

File tree

1 file changed

+17
-32
lines changed

1 file changed

+17
-32
lines changed

packages/rspack/src/util/require.ts

Lines changed: 17 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -23,40 +23,25 @@ export function nonWebpackRequire(): RequireFn {
2323
return;
2424
}
2525

26+
// Only custom esm loader is supported.
2627
const loaderCode = data?.toString() || "";
27-
28-
// 1. Assume it's a cjs
28+
const codeUrl = URL.createObjectURL(
29+
new Blob([loaderCode], { type: "text/javascript" })
30+
);
2931
try {
30-
// Use `new Function` to emulate CJS
31-
const module = { exports: {} };
32-
const exports = module.exports;
33-
const createRequire = () => {
34-
throw new Error(
35-
"@rspack/browser doesn't support `require` in loaders yet"
36-
);
37-
};
38-
39-
// rslint-disable no-implied-eval
40-
const wrapper = new Function(
41-
"module",
42-
"exports",
43-
"require",
44-
loaderCode
45-
);
46-
47-
wrapper(module, exports, createRequire);
48-
resolve(module.exports);
49-
} catch {
50-
// 2. Assume it's an esm
51-
// Use `import(base64code)` to load ESM
52-
const dataUrl = `data:text/javascript;base64,${btoa(loaderCode)}`;
53-
try {
54-
// biome-ignore lint/security/noGlobalEval: use `eval("import")` rather than `import` to suppress the warning in @rspack/browser
55-
const modulePromise = eval(`import("${dataUrl}")`);
56-
modulePromise.then(resolve);
57-
} catch (e) {
58-
reject(e);
59-
}
32+
// We have to use `eval` to prevent this dynamic import being handled by any bundler.
33+
// Applications should config their CSP to allow `unsafe-eval`.
34+
// In the future, we may find a better way to handle this, such as user-injected module executor.
35+
// biome-ignore lint/security/noGlobalEval: use `eval("import")` rather than `import` to suppress the warning in @rspack/browser
36+
const modulePromise = eval(
37+
`import("${codeUrl}")`
38+
) as Promise<unknown>;
39+
modulePromise.then(module => {
40+
URL.revokeObjectURL(codeUrl);
41+
resolve(module);
42+
});
43+
} catch (e) {
44+
reject(e);
6045
}
6146
});
6247
})

0 commit comments

Comments
 (0)