Skip to content

Instantly share code, notes, and snippets.

@candera
Last active January 26, 2020 00:43
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save candera/fbcfb32a9125004423b8db935e27f570 to your computer and use it in GitHub Desktop.
Save candera/fbcfb32a9125004423b8db935e27f570 to your computer and use it in GitHub Desktop.
Package ClojureScript in a Native EXE
# Update: This micro-blog is now also a guide on clojurescript.org:
# http://clojurescript.org/guides/native-executables
# Hello! This is a micro-post about how to produce native executables
# from ClojureScript source. The basic idea is to produce a
# JavaScript file using the ClojureScript compiler, and then use a
# Node.js tool called nexe (https://github.com/jaredallard/nexe) to
# compile that into an executable. The resulting file can be run
# without requiring a node install on the target machine, which can
# be handy.
# nexe works by compiling the v8 engine into an exe that also
# contains your Javascript. So, strictly speaking, your program
# itself is not being compiled ahead of time. But if what you're
# after is the packaging convenience of an EXE, IMO this remains
# a useful technique.
# Install node and nexe
brew install node
npm install nexe -g
# Make a little hello world file
mkdir -p /tmp/nexe-test/src
cd /tmp/nexe-test
cat > src/hello.cljs <<EOF
(ns hello)
(enable-console-print!)
(println "Hello world!")
EOF
# Fire up a REPL and compile the ClojureScript
wget https://github.com/clojure/clojurescript/releases/download/r1.9.229/cljs.jar
java -cp cljs.jar clojure.main <<EOF
(require 'cljs.build.api)
(cljs.build.api/build "src" {:optimizations :advanced :output-to "out/main.js"})
EOF
# Use nexe to turn the js into a native exe. This will take a while
# the first time, but will be reasonably fast for subsequent runs.
# Read https://xkcd.com/303/ to feel better about this.
nexe -i out/main.js -o hello.exe
# Run it
time ./hello.exe
# It's reasonably fast:
# Hello world!
#
# real 0m0.095s
# user 0m0.070s
# sys 0m0.025s
# Enjoy!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment