[英]How to define target env in compile time while building .cljs?
I want to compile my .cljs
file for both browser and node.js environments, to get server side rendering.我想为浏览器和 node.js 环境编译我的.cljs
文件,以获得服务器端渲染。 As I understand, there's no way to define cljs env in compile time with reader macro conditions like:据我了解,无法在编译时使用阅读器宏条件定义 cljs env,例如:
#?(:clj ...)
#?(:cljs ...)
so, I can't easily tell compiler to process something like #?(:cljs-node...)
in node.js env.所以,我不能轻易地告诉编译器在 node.js env 中处理类似#?(:cljs-node...)
的东西。
Second option I see here is to develop a macro file which will define env at compile time.我在这里看到的第二个选项是开发一个在编译时定义 env 的宏文件。 But how to define that current build is targeting node.js?但是如何定义当前构建的目标是 node.js? May be, I could pass some params somehow to compiler or get :target
compiler param?可能是,我可以以某种方式将一些参数传递给编译器或获取:target
编译器参数?
Here are my boot files:这是我的引导文件:
application.cljs.edn:应用程序.cljs.edn:
{:require [filemporium.client.core]
:init-fns [filemporium.client.core/init]}
application.node.cljs.edn:应用程序.node.cljs.edn:
{:require [filemporium.ssr.core]
:init-fns [filemporium.ssr.core/-main]
:compiler-options
{:preamble ["include.js"]
:target :nodejs
:optimizations :simple}}
I am not aware of a public API to achive this.我不知道公共 API 可以实现这一点。 However, you might use cljs.env/*compiler*
dynamic var in your macro to check the target platform (ie NodeJS vs browser) configured with :target
in your :compiler-options
and either emit or suppress the code wrapped in the macro:但是,您可以在宏中使用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"))
Here is up to date code working on org.clojure/clojurescript {:mvn/version "1.11.60"}
这是在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.