Polymer を簡単に試す方法(Yeomanを利用)


Polymer は、Web Components 未対応のブラウザでも Web Components を動かせるようにする JavaScript ライブラリのようです。

たまたま Yeomanの公式のジェネレータ を見つけたので、試してみました。

まず、ジェネレータをインストールし、

$ npm install -g generator-polymer

ジェネレータを起動します。

$ yo polymer

なんか聞かれますが、

よくわからいので適当に Yes を選択します。
完了したら、Grunt で起動してみます。

$ grunt serve

次のように表示されました。

テキストエリアを編集すると、リアルタイムにタイトル部分の文字列が変更されます(データバインディングか何かの機能?)。

中身をみてみる

index.html を見てみます。

app/index.html
<!doctype html>
<html class="no-js">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Polymer WebApp</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- Place favicon.ico and apple-touch-icon.png in the root directory -->

  <!-- build:css styles/main.css -->
  <link rel="stylesheet" href="styles/main.css">
  <!-- endbuild-->

  <script src="bower_components/platform/platform.js"></script>
  <!-- build:vulcanized elements/elements.vulcanized.html -->
  <link rel="import" href="elements/elements.html">
  <!-- endbuild-->
</head>

<body unresolved>

  <div class="hero-unit">
    <yo-greeting></yo-greeting>
    <p>You now have</p>
    <yo-list></yo-list>
  </div>

  <!-- build:js scripts/app.js -->
  <script src="scripts/app.js"></script>
  <!-- endbuild-->
</body>

</html>

上記の rel="import" のタグのところで、外部HTMLファイルを読み込んでるっぽい。
これが Web Components の HTML Imports という機能かな。

また、<yo-greeting></yo-greeting> <yo-list></yo-list> は、Custom Elements の機能である様子。
このエレメントの定義が書かれてそうな yo-greeting.html を開いてみます。

app/elements/yo-greeting.html
<link rel="import" href="../bower_components/polymer/polymer.html">

<polymer-element name="yo-greeting"  attributes="">
  <template>
    <style>
      /* styles for the custom element itself - lowest specificity */
      :host { display: block; }
      /*
      style if an ancestor has the different class
      :host-context(.different) { }
      */
    </style>
    <h1>{{ greeting }}, {{ greeting }}!</h1>
    <span>Update text to change the greeting.</span>
    <input type="text" value="{{ greeting }}">
  </template>
  <script>
    Polymer({
      greeting : '\'Allo'
    });
  </script>
</polymer-element>

本来の Web Components では <element>タグですが、この例のように polymer-element タグで同じ機能が実現できるようです。

ほか

bower_components 配下に、色々なものが大量にインストールされてました(そういえば yo した時に結構時間かかったな..)。

UI 部品もいろいろ揃っているようです。サンプルも同梱されているので、機会があったらまた触ってみようと思います。