Skip to content

Commit 79d9795

Browse files
committed
fix(plugin-runtime): fix document CLI compatibility with ESM lib format
1 parent 033540d commit 79d9795

2 files changed

Lines changed: 21 additions & 5 deletions

File tree

.changeset/funny-turkeys-switch.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@modern-js/runtime': patch
3+
---
4+
5+
fix(plugin-runtime): fix document CLI compatibility with ESM lib format
6+
7+
fix(plugin-runtime): 修复 document CLI 在 ESM 构建格式下的兼容性问题

packages/runtime/plugin-runtime/src/document/cli/index.ts

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,12 @@ const processCommentPlaceholders = (html: string): string => {
181181

182182
// load CommonJS module from code string (evaluated in Node), returns exports
183183
const requireFromString = (code: string, filename: string) => {
184-
const m = new Module.Module(filename, module.parent as Module);
184+
const m = new Module.Module(
185+
filename,
186+
process.env.MODERN_LIB_FORMAT === 'esm'
187+
? undefined
188+
: (module.parent as Module),
189+
);
185190
m.filename = filename;
186191
// set proper resolution paths for nested requires
187192
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
@@ -269,10 +274,14 @@ const applyExternalsPlugin = (child: Compiler, compiler: Compiler) => {
269274
};
270275

271276
const generateEntryCode = (docPath: string, _entryName: string): string => {
272-
const runtimeAPI = require.resolve('../');
273-
const esmRuntimeAPI = runtimeAPI
274-
.replace(`cjs`, `esm`)
275-
.replace(/.js$/, '.mjs');
277+
const runtimeAPI =
278+
process.env.MODERN_LIB_FORMAT === 'esm'
279+
? // @ts-ignore
280+
import.meta.resolve('../index.mjs')
281+
: require.resolve('../');
282+
const esmRuntimeAPI = runtimeAPI.endsWith('.mjs')
283+
? runtimeAPI
284+
: runtimeAPI.replace(`cjs`, `esm`).replace(/\.js$/, '.mjs');
276285

277286
return `import React from 'react';
278287
import ReactDomServer from 'react-dom/server';

0 commit comments

Comments
 (0)