Skip to content

Commit

Permalink
fix: dynamic import to work in eval (#385)
Browse files Browse the repository at this point in the history
  • Loading branch information
privatenumber authored Nov 14, 2023
1 parent 0e52ad8 commit 6eac49b
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 8 deletions.
11 changes: 3 additions & 8 deletions src/utils/transform/transform-dynamic-import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@ import MagicString from 'magic-string';
import type { RawSourceMap } from '../../source-map';
import { parseEsm } from '../es-module-lexer';

const handlerName = '___tsxInteropDynamicImport';

// Prefixed with a newline since there could be a comment on the last line (e.g. sourcemap comment)
const handleEsModuleFunction = `\nfunction ${handlerName}${(function (imported: Record<string, unknown>) {
const toEsmFunctionString = ((imported: Record<string, unknown>) => {
const d = 'default';
const exports = Object.keys(imported);
if (
Expand All @@ -19,9 +16,9 @@ const handleEsModuleFunction = `\nfunction ${handlerName}${(function (imported:
}

return imported;
}).toString().slice('function'.length)}`;
}).toString();

const handleDynamicImport = `.then(${handlerName})`;
const handleDynamicImport = `.then(${toEsmFunctionString})`;

const esmImportPattern = /\bimport\b/;

Expand All @@ -46,8 +43,6 @@ export const transformDynamicImport = (
magicString.appendRight(dynamicImport.se, handleDynamicImport);
}

magicString.append(handleEsModuleFunction);

const newCode = magicString.toString();
const newMap = magicString.generateMap({
source: filePath,
Expand Down
3 changes: 3 additions & 0 deletions tests/specs/smoke.ts
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,9 @@ export default testSuite(async ({ describe }, { tsx }: NodeApis) => {
}
});
const importWorksInEval = async () => await import('./js/index.js');
(0, eval)(importWorksInEval.toString())();
// .json
import * as json from './json/index.json';
import './json/index';
Expand Down

0 comments on commit 6eac49b

Please sign in to comment.