Skip to content

Instantly share code, notes, and snippets.

@klaufir
Last active October 10, 2015 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klaufir/c9bc10b3865b2d87d816 to your computer and use it in GitHub Desktop.
Save klaufir/c9bc10b3865b2d87d816 to your computer and use it in GitHub Desktop.

Clojure Modules HOWTO

Referencing a module from a project

  1. Create new project

    lein new app [appname]
    
  2. (optional) Search for a module you want to add to your project

    lein search [modulename]
    
  3. Reference the module in project.clj under the :dependencies by its identifier which is given in the form of [group-id/artifact-id version-string]. In the following example we add the [org.clojure/data.json "0.2.5"] dependency.

    :dependencies [[org.clojure/clojure "1.6.0"]
                   [org.clojure/data.json "0.2.5"]]
  4. (optional) You can make lein explicitly download the dependencies by

    lein deps
    

Next time you do a lein repl or M-x cider-jack-in lein will download [org.clojure/data.json "0.2.5"] and start the java REPL with [org.clojure/data.json "0.2.5"] loaded.

###Usage from REPL

When you start lein REPL from the project directory lein will then look for the :dependencies key in project.clj, sees [org.clojure/data.json "0.2.5"] and appends the path for the [org.clojure/data.json "0.2.5"] library to the classpath when starting the java process for the REPL.

  1. Start the REPL

lein repl

or in emacs: M-x cider-jack-in

  1. Load the namespace of the dependency in lein repl by referencing the namespace of the library. here the the namespace for [org.clojure/data.json "0.2.5"] is clojure.data.json.

    (require '[clojure.data.json])

    Now it is possible to use functions from clojure.data.json:

    (clojure.data.json/read-str "{\"a\": [1,2,3]}")
    => {"a" [1 2 3]}

    Alternatively you can alias the namespace

    (require '[clojure.data.json :as json])

    Usage:

    (json/read-str "{\"a\": [1,2,3]}")
    => {"a" [1 2 3]}

Usage from .clj files

  1. At the top of the clj file, you have a namespace specification like (ns myproj.core) add to this namespace the :require key to reference a namespace.

    (ns myproj.core
        (:require [clojure.data.json]))

Alternatively you can use a shorter name.

```clojure
(ns myproj.core
    (:require [clojure.data.json :as json]))
```

Additional reading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment