gpt4 book ai didi

node.js - 如何在构建 .cljs 时在编译时定义目标环境?

转载 作者:太空宇宙 更新时间:2023-11-04 00:15:13 26 4
gpt4 key购买 nike

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

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

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

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

这是我的启动文件:

application.cljs.edn:

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

application.node.cljs.edn:

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

最佳答案

我不知道有公共(public) API 可以实现此目的。但是,您可以使用 cljs.env/*compiler*宏中的动态 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"))

关于node.js - 如何在构建 .cljs 时在编译时定义目标环境?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47483193/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com