2
votes

I am stuck with creating a macro for clojurescript. Can you give a step-by-step instruction on how to include a macro in clojurescript? The folder structure I am looking for is like this

+ src/
|    clj/
|       test_app/
|           macros.clj
|    cljs/
|        test_app/
|           example.cljs
| project.clj

Can you give an example for each of the 3 files? I am looking for a solution that is compatible with lein cljsbuild auto .

1

1 Answers

4
votes

This is a macro that allows you to include files in cljs at compile time. For example, when doing i18n, I save all the language strings on a translations.edn file. I then include it at compile time using a macro in /clj/test_app/macros.clj:

(ns test-app.macros
  (:import java.io.File))

(defmacro load-edn
  "Reads a file and returns it as a string"
  [relative-path]
  (slurp relative-path))

In cljs/test_app/example.cljs

(ns test-app.example
  (:require [cljs.reader :as reader])
  (:require-macros [test-app.macros :as m])
  (:use [net.unit8.tower :only [t]]))

(def i18n (reader/read-string (m/load-edn "resources/lang/translations.edn")))

(defn lang-map
  "Wrapper around tower's t adding the configuration map"
  [language & args]
  (apply t language i18n args))

This should work if you start from cljs-kickoff [1] and add [net.unit8/tower-cljs "0.1.0"] to your dependencies.

[1] https://github.com/konrad-garus/cljs-kickoff