Skip to content

Instantly share code, notes, and snippets.

@v6ak
Last active October 19, 2023 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save v6ak/ccd0cadb43993afa854769519646ed46 to your computer and use it in GitHub Desktop.
Save v6ak/ccd0cadb43993afa854769519646ed46 to your computer and use it in GitHub Desktop.
Hack for using Scala.js + ES modules + Google Closure Compiler
var require;
// scala.js externs
//var Object;
Object.prototype.constructor;
Object.prototype.toString;
Object.prototype.$classData;
//var Array;
Array.prototype.length;
//var Function;
Function.prototype.call;
Function.prototype.apply;
//var NaN = 0.0/0.0; //, /*Infinity = 1.0/0.0,*/ undefined = void 0;
#!/bin/bash
# safety settings
set -u
set -e
set -o pipefail
DIR="$(dirname -- "$(realpath -- "$0")")"
echo $DIR
cd "$DIR"/zbdb-stats/client/target/scala-3.3.1/zbdb-stats-client-opt
## Idenpotent in-place fixes
# Current Closure Compiler doesn't like the escape sequence, so fix it
sed -i 's/_\\uff3fself/_xxuff3fselfg/' internal-*.js
# Replace imports with requires for external libraries
sed -i 's#import \* as \([^ ]\+\) from \("[^.].*"\);#const \1 = require(\2);#' internal-*.js
# Create a launcher script
echo 'import * as App from "./client.js";
App.main(null);
' > client.run.js
## Compilation
npx google-closure-compiler@v20220202 \
-O ADVANCED \
--externs "$DIR"/externs.js \
--language_in=ES_NEXT \
--module_resolution=NODE \
client.run.js client.js internal-*.js \
--entry_point=client.run.js \
> opt.js
## Postprocessing
# Replace requires by imports except the last one
lasthash=""
while [ "$lasthash" != "$(sha256sum opt.js)" ]; do
lasthash="$(sha256sum opt.js)"
sed -i 's/const \([^=]\+\)=require(\("[^"]\+"\)),/import * as \1 from \2; const /' opt.js
done
# Replace the last one
lasthash=""
while [ "$lasthash" != "$(sha256sum opt.js)" ]; do
lasthash="$(sha256sum opt.js)"
sed -i 's/const \([^=]\+\)=require(\("[^"]\+"\));/import * as \1 from \2;/' opt.js
done
## Show the output stats
wc -c opt.js
ls -lh opt.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment