Skip to content

Commit

Permalink
Adjusts bundler output to work with Node. (#20)
Browse files Browse the repository at this point in the history
## 💸 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!
  • Loading branch information
gunsch authored May 21, 2024
1 parent 55a90fa commit 788f519
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/bundler/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
)
}

Expand Down

0 comments on commit 788f519

Please sign in to comment.