我经常发现自己在 clojurescript 中定义的命名空间只包含一个通过 def 或 defn 创建的 var,我将在该命名空间之外使用它。
这在使用 reagent 时尤为常见。 ,我在单独的文件/命名空间中定义我的组件,并且我只在命名空间之外使用这些单个组件。
(ns project.components.component-name)
(defn component-name ...)
所以我以这种方式导入它们,我发现它非常重复且不清楚,因为命名空间和组件都使用了一个名称:
project.components.component-name :as [component-name]
component-name/component-name
或劣等 :refer (因为 var 来自另一个命名空间不太明显)
project.components.component-name :refer [component-name]
component-name
我知道在 ECMAScript 中有一个有用的模式:
export default function () { ... };
那么Clojure中有这样的东西吗?或者也许有一些既定的约定?
下面是我最近开始使用的约定,我对此非常不确定。
(ns project.components.component-name)
(defn _ ...)
project.components.component-name :as [component-name]
然后将其用作
component-name/_
最佳答案
下划线通常用于表示您在 Clojure 中不关心的值,因此我强烈建议您避免使用 _
作为函数名。例如,您经常会在野外看到这样的代码:
;; Maybe when destructuring a let. Kinda contrived example.
(let [[a _ _ d] (list 1 2 3 4)]
(+ a d 10))
;; Quite often in a protocol implementation where we don't care about 'this'.
(defrecord Foo []
SomeProtocol
(thing [_ x]
(inc x)))
在命名空间中使用单个 var 并没有错,尽管我可能只会在有合理的功能块时才引入命名空间。您可以尝试使用像
my-app.components
这样的命名空间在那里你保留所有的小东西,直到它们大到足以保证一个专用空间。类似的东西:(ns my-app.components
;; The profile stuff is really big lets say.
(:require [my-app.components.profile :as profile]))
(defn- items->ul
[items]
[:ul (map #(vector :li (:text %)) items)])
(defn- render-nav
[state]
[:nav (-> state deref :nav-items items->ul)])
(defn- render-footer
[state]
[:footer (-> state deref :footer-items items->ul)])
(defn render-layout
[state]
[:html
[:head [:title (:title @state)]]
[:body
[:main
(render-nav state)
(profile/render-profile (-> state deref :current-user))
(render-footer state)]]])
关于clojure - clojure/clojurescript 中单个 var 命名空间的命名约定是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42701553/