Skip to content

Instantly share code, notes, and snippets.

@thheller
Last active September 7, 2021 13:25
Show Gist options
  • Save thheller/b652ac96231560a2cca9003534232980 to your computer and use it in GitHub Desktop.
Save thheller/b652ac96231560a2cca9003534232980 to your computer and use it in GitHub Desktop.

shadow-cljs code split

Quick comparison to the cljs.loader recently added to CLJS.

Things shadow-cljs does for you:

  • enable-console-print! is a config option, you do not need to call it
  • loader/set-loaded! will be injected for you as well

Install

# install globally to have gain access to shadow-cljs command
yarn global add shadow-cljs

# add to project (optional but recommended)
yarn add --dev shadow-cljs

# create initial config
shadow-cljs init

Configuration

Modify default shadow-cljs.edn config

{:source-paths ["src"]
 :dependencies []

 :builds ;; one build with id split (used by shadow-cljs commands)
 {:split {:target :browser
          :output-dir "public/js"
          :asset-path "/js"

          :module-loader true
          :modules
          {:base ;; there is no implicit :cljs-base module
           {:entries [cljs.core]}
           :foo
           {:entries [foo.core]
            :depends-on #{:base}}
           :bar
           {:entries [bar.core]
            :depends-on #{:base}}}

          :devtools ;; optional but useful during development
          {:http-root "public"
           :http-port 8080}}}}

src/foo/core.cljs

(ns foo.core
  (:require [shadow.loader :as loader]))
  
(println "I'm foo!")

;; plain JS, no goog.events
(doto (js/document.getElementById "button")
  (.addEventListener "click"
    (fn [e]
        (-> (loader/load "bar")
            (.then #((resolve 'bar.core/woz)))
            ))))

src/bar/core.cljs

(ns bar.core)

(println "I'm bar!")

(defn woz []
  (println "WOZ!"))

public/index.html

<html>
    <body>
         <button id="button">Load Bar!</button>
         <script src="js/base.js" type="text/javascript"></script>
         <script src="js/foo.js" type="text/javascript"></script>
    </body>
</html>

Building

shadow-cljs watch split

open http://localhost:8080

# if you'd like a CLJS REPL (while watch is running)
shadow-cljs cljs-repl split

# build :advanced release build
shadow-cljs release split

The development HTTP server is currently not available for release builds, that will change in the future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment