22

How to call ClojureScript code from Javascript (not the other way around !).

It is already possible to call Clojure from Java, but I don't know how to do the equivalent in ClojureScript.

1

2 Answers 2

32

Export the functions you want to have available in js by using ^:export, then simply call it as my.ns.fn()

cljs:

(ns hello-world.core)

(defn ^:export greet [] "Hello world!")

js:

hello_world.core.greet()

See the accepted answer to "Clojurescript interoperability with JavaScript" for detailed info.

Sign up to request clarification or add additional context in comments.

1 Comment

As of 2020, ^:export is redundant.
8

Clojurescript compiles to Javascript so you can use it as is.

Datascript is a great source of inspiration to learn this, it is written in Clojurescript and is used via vanilla javascript javascript as is.

In pseudo code that gives:

<script src="https://github.com/tonsky/datascript/releases/download/0.11.6/datascript-0.11.6.min.js"></script>
...
...
var d = require('datascript');
// or 
// var d = datascript.js;

var db = d.empty_db();
var db1 = d.db_with(db, [[":db/add", 1, "name", "Ivan"],
                       [":db/add", 1, "age", 17]]);
var db2 = d.db_with(db1, [{":db/id": 2,
                        "name": "Igor",
                        "age": 35}]);

var q = '[:find ?n ?a :where [?e "name" ?n] [?e "age" ?a]]'; 
assert_eq_set([["Ivan", 17]], d.q(q, db1));
assert_eq_set([["Ivan", 17], ["Igor", 35]], d.q(q, db2));

You can see the interop section of this blog entry.

Lastly, go through the datascript javascript-based test suite.

1 Comment

Thank you that was useful, especially this: github.com/tonsky/datascript/blob/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.