Skip to content

Instantly share code, notes, and snippets.

@rauhs
Last active April 3, 2017 13:49
Show Gist options
  • Select an option

  • Save rauhs/7c6c5da2acfd7d4eee30f58c6262f7c1 to your computer and use it in GitHub Desktop.

Select an option

Save rauhs/7c6c5da2acfd7d4eee30f58c6262f7c1 to your computer and use it in GitHub Desktop.
(ns cljs-snippeter
(:require
[clojure.walk :as walk]
[clojure.string :as str]
[clj-http.client :as client]))
(def ^:dynamic *compiling-ns* nil)
(defn compile-form
[form]
(require 'cljs.analyzer.api)
(require 'cljs.compiler.api)
(-> (cljs.analyzer.api/analyze
(assoc-in (cljs.analyzer.api/empty-env) [:ns :name] *compiling-ns*)
form)
(cljs.compiler.api/emit)))
#_(compile-form '(set! js/XX (fn [x] x)) )
(defn optimize-js
[js]
(client/request {:method :post
:url "https://closure-compiler.appspot.com/compile"
:as :json
:coerce :always
:throw-exceptions false
:form-params {:js_code (str js)
:output_info "compiled_code"
;:compilation_level "SIMPLE_OPTIMIZATIONS"
:compilation_level "ADVANCED_OPTIMIZATIONS"
:use_closure_library true
:output_format "json"}}))
(defn partition-when
"Applies f to each value in coll, starting a new partition each time f
returns a true value. Returns a lazy seq of partitions. Returns a stateful
transducer when no collection is provided."
[f coll]
(lazy-seq
(when-let [s (seq coll)]
(let [fst (first s)
run (cons fst (take-while #(not (f %)) (next s)))]
(cons run (partition-when f (seq (drop (count run) s))))))))
(defn goog-provides-ns
[bodys]
(first
(keep
(fn [[fn-call the-ns]] (when (= 'goog/provide fn-call)
(symbol the-ns)))
bodys)))
(defn partition-by-ns
[forms]
(partition-when (fn [[s]] (= s 'goog/provide)) forms))
(defmacro some-macro
[& args]
(apply list 'js-obj args))
(defmacro to-js
[min? & body]
(cond-> (str/join
"\n"
(for [part (partition-by-ns body)]
;; Avoid missing ns errors:
(binding [*out* (java.io.StringWriter.)
*err* (java.io.StringWriter.)
*compiling-ns* (goog-provides-ns part)]
(compile-form (walk/macroexpand-all `(do ~@part))))))
min? (optimize-js)))
#_(to-js true
(goog/provide "some_alerter")
(defn alert_me [] (js/alert "hi"))
(goog/provide "some_user")
(goog/require "some_alerter")
(defn ^:export do_it [x]
(some-macro "foo" "hi")
(some_alerter/alert_me))
(defn foo [x] x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment