From 1b85e259b4dd4ee0db14caa46cf4cd4595defc60 Mon Sep 17 00:00:00 2001 From: Andrew Gunsch Date: Mon, 20 May 2024 19:34:29 -0700 Subject: [PATCH 1/2] Adjusts bundler output to work with Node. --- src/bundler/compiler.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/bundler/compiler.ts b/src/bundler/compiler.ts index 178cdba..b094dca 100644 --- a/src/bundler/compiler.ts +++ b/src/bundler/compiler.ts @@ -21,10 +21,14 @@ export function compile(env: tsvfs.VirtualTypeScriptEnvironment): string { const src = env.languageService.getEmitOutput(appEntrypointFilename).outputFiles[0] ?.text ?? '' - // Adapt bundle CommonJS output to format expected by runtime-lite. + // Adapt bundle CommonJS output to format expected by our runtimes. + // This is a light hack that satisfies two different runtime needs: + // * runtime-lite needs `exports` to be defined and aliased to `module.exports` like so. + // * Node wraps the file in a function that provides `module` and `exports` already, so + // needs them not to be overwritten. return src.replace( /^"use strict";/, - '"use strict"; module.exports = {}; const {exports} = module;' + '"use strict"; if (!module.exports) { module.exports = {}; var exports = module.exports; }\n' ) } From 4bdc20f4fd545fd77bbf55d1d2e69d81fe322fc5 Mon Sep 17 00:00:00 2001 From: Andrew Gunsch Date: Tue, 21 May 2024 09:06:29 -0700 Subject: [PATCH 2/2] more comments --- src/bundler/compiler.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/bundler/compiler.ts b/src/bundler/compiler.ts index b094dca..aa6c50e 100644 --- a/src/bundler/compiler.ts +++ b/src/bundler/compiler.ts @@ -23,9 +23,15 @@ export function compile(env: tsvfs.VirtualTypeScriptEnvironment): string { ?.text ?? '' // Adapt bundle CommonJS output to format expected by our runtimes. // This is a light hack that satisfies two different runtime needs: - // * runtime-lite needs `exports` to be defined and aliased to `module.exports` like so. - // * Node wraps the file in a function that provides `module` and `exports` already, so - // needs them not to be overwritten. + // 1. runtime-lite needs `exports` to be defined and aliased to `module.exports` like so. + // 2. Node wraps the bundle's code in this function: + // + // (function(exports, require, module, __filename, __dirname) { + // // [ bundle code here ] + // }); + // + // We can't overwrite `module.exports` (the resulting bundle won't actually export what + // it needs to), and we can't declare `exports` with const/let ("already been declared"). return src.replace( /^"use strict";/, '"use strict"; if (!module.exports) { module.exports = {}; var exports = module.exports; }\n'