WebComponentsとPolymerをかんたんにさわってみた
6855 ワード
WebComponentsとは?
HTMLで使える独自のタグを定義していつでも呼び出せるようにする技術。
フレームワークに依存しないため、再利用性が高い。
ライブラリやフレームワークが不要。
HTML/CSS/JavaScriptだけで構築することができる。
4つの仕様で構成される。
- Custom Elements
- Shadow DOM
- HTML Imports
- HTML Template
Webcomponentsを使ってみる
サンプルプログラムで表示してみる。
html
<html>
<head>
<style>
span {
color: white;
background-color: black;
}
</style>
<template id="hello">
<style>
.colored {
color: red;
}
</style>
<div class="colored">
Hello, <span><content></content></span>!
</div>
</template>
<script>
class HelloDiv extends HTMLElement {
constructor() {
super();
const template = document.querySelector('#hello');
const node = document.importNode(template.content, true);
this.createShadowRoot();
this.shadowRoot.appendChild(node);
}
}
customElements.define('hello-tag', HelloDiv);
</script>
</head>
<body>
<div><span>fugafuga</span></div>
<hello-tag>World</hello-tag>
<div><span>hogehoge</span></div>
<hello-tag>WebComponents</hello-tag>
</body>
</html>
例えば
<hello-tag>World</hello-tag>
こう書くと
<template id="hello">
<style>
.colored {
color: red;
}
</style>
<div class="colored">
Hello, <span><content></content></span>!
</div>
</template>
の中にタグで囲まれた部分、今回だとWorldが入ってきて、
Hello, World
と赤字で表示されます。
ブラウザで参照してみる
Firefoxから参照したとき
Chrome以外は対応していないモジュールが多いらしい、ブラウザごとの実装に差異が結構ある。
→Polymerを使えばOK!
Polymerの特徴
- WebComponentsの機能を利用できるOSSライブラリ。
WebComponentsをやってみる
Polymer-CLIのインストール
npm install -g polymer-cli
mkdir polymer-sample
cd polymer-sample
起動する
polymer-init
スターターキットを選択する
? Which starter template would you like to use?
polymer-3-starter-kit
Polymer serveを実行
polymer serve
info: [cli.command.serve] Files in this directory are available under the following URLs
applications: http://127.0.0.1:8001
reusable components: http://127.0.0.1:8001/components/polymer-starter-kit/
Netlifyへデプロイ
GithubやGitLabのリポジトリと連携してホスティングできるサービス。無料。便利。
実際にデプロイしたもの
まとめ
全体の流れはこんな感じ。
部品化できるので便利っぽい。
WebComponentsをもっとさわる必要あり。
Author And Source
この問題について(WebComponentsとPolymerをかんたんにさわってみた), 我々は、より多くの情報をここで見つけました https://qiita.com/umeee/items/e0ecf8cf6daae6c41907著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .