Riot.js触ってみた


はじめに

Riot.js勉強のため、Live demoのコードを参考にまとめてみました。

Riot.jsとは?

Riotは、公式ページに

A REACT- LIKE, 2.5KB USER INTERFACE LIBRARY

とあるように、Reactを意識して作られた超軽量のUIライブラリで、ビュー部分(コンポー>ネント)に特化しているのが特長です。Vue.jsとかとも同類です。Riot 1.0も「超軽量」という点で、一時注目を集めました。

そのRiotが、2.0で趣向を変えてJSX的なプリコンパイルの仕組みを取り入れて、>ReactとPolymerのいいとこ取りのような感じになっています。ただし、次のような大きな違いがあります。

React: JavaScript(JSX)の中に、HTMLを書く
Riot: HTMLの中に、JavaScriptやCSSを書く
スクリプトサイズは24分の1。Reactが優に100KBを越えるのに対して、Riotはたった>5.7KB。gzip圧縮かければ2.5KB。ちなみに、Riotの開発元のMUUTは既存サイトにエンベッドして使う、フォーラムツールを作っているチームです。(Disqusみたいなやつ)

こちらより引用

Live demoのコードを理解する

サンプルコード

index.html
<html>
  <head>
    <title>Hello Riot.</title>
  </head>
  <body>

    <sample></sample>

    <script type="riot/tag" src="sample.tag"></script>
    <script src="https://cdn.jsdelivr.net/riot/3.0/riot+compiler.min.js"></script>

    <script>riot.mount('sample')</script>
  </body>
</html>
sample.tag
<sample>
  <h3>{ message }</h3>
  <ul>
    <li each={ techs }>{ name }</li>
  </ul>

  <script>
    this.message = 'Hello, Riot!'
    this.techs = [
      { name: 'HTML' },
      { name: 'JavaScript' },
      { name: 'CSS' }
    ]
  </script>

  <style>
    :scope { font-size: 2rem }
    h3 { color: #444 }
    ul { color: #999 }
  </style>
</sample>

表示

サンプルコードについて

Riot.jsでは、部品(カスタムタグ)を組み合わせて、ページを作成しています。
サンプルコードでは、作成したsampleタグをindex.htmlで呼び出しています。

index.html

1.sampleタグを配置する

<sample></sample>

2.sampleタグを読み込む

<script type="riot/tag" src="sample.tag"></script>

3.sampleタグを(ブラウザで)コンパイルする

<script src="https://cdn.jsdelivr.net/riot/3.0/riot+compiler.min.js"></script>

4.sampleタグをマウントする

<script>riot.mount('sample')</script>

また、下記のようにすると、ページ上すべてのカスタムタグをマウントできます。

<script>riot.mount('*')</script>

sample.tag

次に、sample.tagを見ていきます。

1.タグを定義する

<sample>
   ~
</sample>

2.html

<h3>{ message }</h3>
<ul>
  <li each={ techs }>{ name }</li>
</ul>

{}は、jsで定義している変数を参照しに行く。
eachは、techsの中身を回してる。

3.script

<script>
  this.message = 'Hello, Riot!'
  this.techs = [
    { name: 'HTML' },
    { name: 'JavaScript' },
    { name: 'CSS' }
  ]
</script>

4.style

<style>
  :scope { font-size: 2rem }
  h3 { color: #444 }
  ul { color: #999 }
</style>

Scoped CSSを使用している。

その他