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

如何在Babashka中从同目录脚本导入函数?

问题描述

有一个Babashka脚本common.clj:

#!/usr/bin/env bb

(ns common)

(defn my-function []
  (println "do something"))

尝试在另一个脚本example.clj中导入该函数:

#!/usr/bin/env bb

(ns example
  (:require [common :as c]))

(c/my-function)

运行example.clj时,尽管common.clj文件存在,仍报错:

(:require [common :as c]))
^--- Could not locate common.bb, common.clj or common.cljc on classpath.
解决方案

Babashka默认不会将当前目录自动加入类路径,因此需要手动配置类路径或调整导入方式,以下是三种可行的修复方法:

方法1:运行时指定类路径

执行example.clj时,通过-cp参数将当前目录(.)添加到类路径:

bb -cp . example.clj

方法2:脚本内动态设置类路径

在example.clj开头添加代码,将当前工作目录追加到类路径:

#!/usr/bin/env bb

(alter-var-root #'clojure.core/*classpath*
                (fn [current-cp]
                  (str current-cp ":" (System/getProperty "user.dir"))))

(ns example
  (:require [common :as c]))

(c/my-function)

方法3:使用相对路径导入

如果两个脚本在同一目录下,可直接用相对路径的语法导入(注意路径前的./):

#!/usr/bin/env bb

(ns example
  (:require ["./common" :as c]))

(c/my-function)

这种方式无需额外配置类路径,Babashka会根据相对路径直接定位文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 10:43:16