如何为clojurescript创建宏

时间:2014-08-29 14:11:01

标签: clojurescript

我很难为clojurescript创建一个宏。你能详细说明如何在clojurescript中包含一个宏吗?我正在寻找的文件夹结构就像这样

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

您能为3个文件中的每个文件举例吗?我正在寻找与lein cljsbuild auto兼容的解决方案。

1 个答案:

答案 0 :(得分:4)

这是一个允许您在编译时将文件包含在cljs中的宏。例如,在执行i18n时,我将所有语言字符串保存在translations.edn文件中。然后我在编译时使用/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))

在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))

如果从cljs-kickoff [1]开始并将[net.unit8/tower-cljs "0.1.0"]添加到依赖项中,这应该有效。

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