Skip to content

Commit

Permalink
fix: use liveRequire to avoid overwrite __webpack__require__
Browse files Browse the repository at this point in the history
  • Loading branch information
Jinbao1001 committed Apr 28, 2024
1 parent fcbd8f5 commit bb67f7c
Showing 1 changed file with 16 additions and 14 deletions.
30 changes: 16 additions & 14 deletions src/client/theme-api/useLiveDemo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,10 @@ export const useLiveDemo = (
const entryFileName = Object.keys(asset.dependencies).find(
(k) => asset.dependencies[k].type === 'FILE',
)!;
const require = (v: string) => {
// why not require?
// https://github.com/airbnb/babel-plugin-dynamic-import-node/blob/a68388870de822183218515a1adbb3e8d7fa9486/src/utils.js#L24
// if just use require, local variable will overwrite __webpack__require__ in the template method
const liveRequire = (v: string) => {
if (v in context!) return context![v];
throw new Error(`Cannot find module: ${v}`);
};
Expand All @@ -119,14 +122,14 @@ export const useLiveDemo = (

if (renderOpts?.renderer && renderOpts?.compile) {
try {
const exports: AgnosticComponentType = {};
const module = { exports };
const liveExports: AgnosticComponentType = {};
const liveModule = { exports: liveExports };
evalCommonJS(entryFileCode, {
exports,
module,
require,
exports: liveExports,
module: liveModule,
require: liveRequire,
});
const component = await getAgnosticComponentModule(exports);
const component = await getAgnosticComponentModule(liveExports);
if (renderOpts.preflight) {
await renderOpts.preflight(component);
}
Expand All @@ -149,20 +152,19 @@ export const useLiveDemo = (
// skip current task if another task is running
if (token !== taskToken.current) return;

const exports: { default?: ComponentType } = {};
const module = { exports };

const liveExports: { default?: ComponentType } = {};
const liveModule = { exports: liveExports };
// initial component with fake runtime
evalCommonJS(entryFileCode, {
exports,
module,
require,
exports: liveExports,
module: liveModule,
require: liveRequire,
});

const newDemoNode = createElement(
DemoErrorBoundary,
null,
createElement(exports.default!),
createElement(liveExports.default!),
);
const oError = console.error;

Expand Down

0 comments on commit bb67f7c

Please sign in to comment.