LoveProgramming
LoveProgramming

Reputation: 2181

How to integrate clojurescript to existing javascript code base?

I'm writing a addon feature in clojurescript using reagent. I would like to use this in a existing react, flux app.

How should I connect the two?

Upvotes: 3

Views: 565

Answers (1)

DaoWen
DaoWen

Reputation: 33019

Since the ClojureScript compiler spits out JavaScript code, integration should be pretty trivial. Just add the ^:export annotation to any ClojureScript definitions that you want to access from your JavaScript code.

; ClojureScript
(ns my-namespace.core)

(defn ^:export my-identity [x] x)
// call from JavaScript
my_namespace.core.my_identity(5); // Notice how "-" is replaced with "_"

If you want to reference JavaScript functions/variables from your ClojureScript code, just prefix the global name with js/.

; Calling global JavaScript function from ClojureScript
(js/alert "Hello!")

Take a look at this blog post on ClojureScript/JavaScript interop for more examples.

The JavaScript Interop section on the ClojureScript Cheatsheet is also a good reference. For example, it documents the clj->js and js->clj functions, which you would need to use to convert between Clojure-style objects (keywords, vectors, maps) and JavaScript-style objects (strings, arrays, maps/objects).

Upvotes: 8

Related Questions