繁体   English   中英

building.cljs 时如何在编译时定义目标环境?

[英]How to define target env in compile time while building .cljs?

我想为浏览器和 node.js 环境编译我的.cljs文件,以获得服务器端渲染。 据我了解,无法在编译时使用阅读器宏条件定义 cljs env,例如:

#?(:clj ...)
#?(:cljs ...)

所以,我不能轻易地告诉编译器在 node.js env 中处理类似#?(:cljs-node...)的东西。

我在这里看到的第二个选项是开发一个在编译时定义 env 的宏文件。 但是如何定义当前构建的目标是 node.js? 可能是,我可以以某种方式将一些参数传递给编译器或获取:target编译器参数?

这是我的引导文件:

应用程序.cljs.edn:

{:require  [filemporium.client.core]
 :init-fns [filemporium.client.core/init]} 

应用程序.node.cljs.edn:

{:require [filemporium.ssr.core]
 :init-fns [filemporium.ssr.core/-main]
 :compiler-options
 {:preamble ["include.js"]
  :target :nodejs
  :optimizations :simple}}

我不知道公共 API 可以实现这一点。 但是,您可以在宏中使用cljs.env/*compiler* dynamic var 来检查在您的:compiler-options中配置了:target的目标平台(即 NodeJS 与浏览器),并发出或抑制包含在宏中的代码:

(defn- nodejs-target?
  []
  (= :nodejs (get-in @cljs.env/*compiler* [:options :target])))

(defmacro code-for-nodejs
  [& body]
  (when (nodejs-target?)
    `(do ~@body)))

(defmacro code-for-browser
  [& body]
  (when-not (nodejs-target?)
    `(do ~@body)))

(code-for-nodejs
  (def my-variable "Compiled for nodejs")
  (println "Hello from nodejs"))

(code-for-browser
  (def my-variable "Compiled for browser")
  (println "Hello from browser"))

这是在org.clojure/clojurescript {:mvn/version "1.11.60"}上工作的最新代码

(ns contrib.cljs-target
  #?(:cljs (:require-macros [contrib.cljs-target]))
  #?(:cljs (:require [goog.object :as object])))

; preferred runtime check for target through public API https://cljs.github.io/api/cljs.core/STARtargetSTAR
#?(:cljs (defn nodejs? [] (= cljs.core/*target* "nodejs")))
#?(:cljs (defn browser? [] (= cljs.core/*target* "default")))

; undocumented hack, only works in macros. https://stackoverflow.com/a/47499855
#?(:clj (defn- cljs-target [] (get-in @cljs.env/*compiler* [:options :closure-defines 'cljs.core/*target*])))

(defmacro do-nodejs  [& body] (if     (= "nodejs" (cljs-target)) `(do ~@body)))
(defmacro do-browser [& body] (if-not (= "nodejs" (cljs-target)) `(do ~@body)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM