From 788f519bef57c39a098b4abc3e140fb4d3f3ca8e Mon Sep 17 00:00:00 2001 From: Andrew Gunsch Date: Tue, 21 May 2024 09:40:46 -0700 Subject: [PATCH] Adjusts bundler output to work with Node. (#20) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## ๐Ÿ’ธ TL;DR Adjusts bundler output to also work with Node. ## ๐Ÿ“œ Details * In Node, `require` calls are wrapped in a function that provides `modules` and `exports`. Redefining them caused the app to not load. * Deleting the `src.replace` line modified here fixed Node, but broke `runtime-lite`, which needs those definitions shimmed in. * The resulting code is a compromise that works in both cases, at the cost of an ugly `var` in the generated code. Sorry about that. ## ๐Ÿงช Testing Steps / Validation * Testing a simple Devvit with Play that registers a custom post until I got it to fully load and render the post! --- src/bundler/compiler.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/bundler/compiler.ts b/src/bundler/compiler.ts index 178cdba..aa6c50e 100644 --- a/src/bundler/compiler.ts +++ b/src/bundler/compiler.ts @@ -21,10 +21,20 @@ 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: + // 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"; module.exports = {}; const {exports} = module;' + '"use strict"; if (!module.exports) { module.exports = {}; var exports = module.exports; }\n' ) }