LoginSignup
38
36

More than 5 years have passed since last update.

ClojureScript入門

Last updated at Posted at 2014-08-26

ClojureScriptで二週間ぐらい遊んでるのでメモ

セットアップ

まずは leiningen いれる
macだったらhomebrewで brew install lein でいい。

通常のチュートリアルではlein new app-name でプロジェクト生成して、cljsbuildプラグインセットアップしてビルドする。

が、今回は練習用スケルトン作ったので使うといい。

bowerとgulpでプロジェクト管理してある。

git clone https://github.com/mizchi-sandbox/cljs-webapp-skeleton
$ npm install -g bower
$ npm install
$ bower install
$ lein cljsbuild once
$ gulp watch

localhost:3000 で開く

REPL

殴って確かめるのが速い。

$ lein trampoline cljsbuild repl-rhino
> 

自動監視とコンパイル

ClojureScriptにおいては自動監視はただの監視以上の意味がある。

project.cljのcljsbuild

  :cljsbuild {
    :builds [{
        :source-paths ["src"]
        :compiler {
          :output-to "public/main.js"
          :optimizations :none
          :pretty-print true}}]})

コンパイル

$ lein cljsbuild once

とするところを onceでなくautoにする

$ lein cljsbuild auto

ClojureScriptで一番重いのはJVMの立ち上げとClojure処理系そのものの起動で、autoだと処理系立ち上げっぱなしのホットスタンバイになるので、速い。
どれぐらい速いかというと、HelloWorldのプロジェクトで最初の一回は7秒ぐらいだが、以降0.4秒ほどになる。
自分は、ClojureScriptを今まで本気で使ってなかった理由がこのコンパイル速度だったので、速度大事。

Hello World!

console.log でダンプしてもいいのだが、 clojureのprintlnを使うと構造体をいい感じでpretty-printしてくれる。
printlnを使うには一行おまじないが必要。

src/main.cljs

(ns main)
(enable-console-print!)
(println "initialized")

名前空間を深くするお約束に従ってない。とりあえず適当に触る分には大丈夫。

メンバアクセスと関数呼び出し

JSでよく書くやつ

window.addEventListener("load", function(){
  console.log("hello");
});

これをclojurescriptで書く

(.addEventListener js/window "load" (fn []
  (.log console "hello"))

..で深いプロパティフィールドにアクセスする

(.. js/window -document -body)

代入

window.onload = function(){}
  console.log("hello");
});
(!set (.-onload js/window) (fn [] (.log console "hello"))

あとはまあなんとかなるのでは適当

外部モジュールの読み込み

src/hellocljs/foo.cljs

(ns hellocljs.foo)
(defn hello [] (println "hello"))

fooに名前をつけて読み込む

(ns hellocljs.core
  (:require [hellocljs.foo :as foo]))
(foo/hello)

helloだけ呼び出す。

(ns hellocljs.core
  (:use [hellocljs.foo :only [hello]]))
(hello)

マクロ

拡張子cljsの中でマクロを書くことは許されていない

debug.clj

(ns hellocljs.debug)
(defmacro debug [expr]
  `(let [result# ~expr]
    (println "Evaluatng:" '~expr)
    (println "Result:" result#)
    result#))

読み込む

(ns hellocljs.core
  (:require-macros
    [hellocljs.debug :as debug]
    ))

(debug/debug (+ 3 3))
;Evaluatng: (+ 3 3)
;Result: 6

plugin

ここらへん使ってる

自分はomを使いたいがためにclojurescript始めたと行っても良い。

38
36
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
36