Last Updated: January 28, 2019
·
3.981K
· pierrel

ClojureScript browser REPL

tldr;
https://github.com/pierrel/bare-clojurescript-repl

Setup

Start a new compojure project

$ lein new compojure my-project

Add lein-cljsbuild to the list of plugins:

:plugins [[lein-ring "0.8.2"]
          [lein-cljsbuild "0.3.0"]]

Add the cljsbuild config:

:cljsbuild {:builds [{:source-paths ["src/cljs"]
                      :compiler {:output-to "resources/public/development.js"
                                 :optimizations :whitespace
                                 :pretty-print true}}]}

Create the cljs file in src/cljs/repl.cljs:

(ns my-project.repl
  (:require [clojure.browser.repl :as repl]))
(repl/connect "http://localhost:9000/repl")

Create an html file in which to include the js, resources/public/index.html:

<!DOCTYPE html>
<html>
  <body>
  <div id="heading">
    <h1>Something here</h1>
  </div>
  <script src="/development.js"></script>
  </body>
</html>

Setup the server handler src/my_project/handler.cljs:
to include the ring response util (in the :require statement):

[ring.util.response :as resp]

to serve the index file (in app-routes):

(GET "/" [] (resp/file-response "index.html" {:root "resources/public"}))

Run it

Start the builder in one terminal session:

$ lein cljsbuild auto

Start the repl in another (once that's been compiled):

$ lein trampoline cljsbuild repl-listen

Start the server in another (once the listener is listening: you'll see "ClojureScript:cljs.user>" as the prompt):

$ lein ring server

Once the server is running it should open a browser, if not hit http://localhost:3000. Once that's loaded go to the repl (the one with "ClojureScript:cljs.user>") and start doing stuff!

(+ 1 1)
=> 2
(goog.dom/appendChild (goog.dom/getElement "heading") (goog.dom/htmlToDocumentFragment "<p>something down here</p>")
=> nil ; check the webpage

Discussion

The main takeaway from this is

  • Use cljsbuild's "repl-listen"
  • Run the compiled js over http
  • Do (clojure.browser.repl/connect "http://localhost:9000/repl") from somewhere on the page (in cljs)

It's really annoying to have to create a whole compojure project just to get this started, I know, but I only did it because you can't just serve the index.html file right off the filesystem (using the file:// protocol) since the cljsbuild repl listens over http. You can also just serve the index.html (and compiled js) from apache or similar if that's easier. Besides that this is the best damned way to develope a cljs project. I mean you can edit the html live. What more do you need?

1 Response
Add your response