You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ClojureScript中复制命名空间或创建模块别名?

在ClojureScript中批量导出/别名模块内容的实用方案

1. 宏批量导出目标模块的所有公共变量

如果需要保留my.thing作为导出入口,但不想手动逐个定义变量,可以用宏自动完成批量绑定:

(ns my.thing
  (:require [other.thing]))

(defmacro export-all [target-ns]
  `(do
     ~@(for [[sym var] (ns-publics target-ns)]
         `(def ~sym ~var))))

;; 执行宏,批量导出other.thing的所有公共变量
(export-all 'other.thing)

ns-publics会返回目标命名空间所有公共Var的键值对,宏遍历这些内容自动生成def语句,一次性完成所有变量的绑定,无需手动逐个编写。

2. 无需单独文件:直接在使用处简化引用

如果不需要专门的导出模块,只是想在自己的代码里快速使用other.thing的内容,有两种方式:

  • 直接引用所有变量:用:refer :all将目标模块的公共变量直接引入当前命名空间:
    (ns my.some-module
      (:require [other.thing :refer :all]))
    
    ;; 直接使用a、b、c等变量
    (println a)
    
  • 创建命名空间别名:用:as给目标模块起简写别名,通过别名访问变量,既简洁又避免命名冲突:
    (ns my.some-module
      (:require [other.thing :as t]))
    
    ;; 通过别名t访问变量
    (println t/a)
    

3. 批量重命名导出(可选)

如果需要对导出的变量统一重命名(比如添加前缀),可以结合:rename和宏生成映射规则:

(ns my.thing
  (:require [other.thing :as ot :rename ~(into {} 
                                               (for [sym (keys (ns-publics 'other.thing))]
                                                 [sym (symbol (str "ot-" sym))]))]))

这段代码会把other.thing/a映射为ot-a,other.thing/b映射为ot-b,批量完成自定义规则的重命名绑定。

内容的提问来源于stack exchange,提问作者BnMcGn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 12:01:05