この記事は Riot.js Advent Calendar 2017 13日目の記事です。 昨日は@supple さんによるRiot+ElectronでMarkdownエディタを作る でした。

tl;dr

  • Parcel というJavaScriptのモジュールバンドラを触ってみた
  • webpackなどと比べて設定ファイルなどもいらずとても簡単
  • ホットリロードな開発サーバを簡単に実行できる
  • Riotと組み合わせるのもそれほど難しくない

Parcel + Riot.js

Parcel というJavaScriptのモジュールバンドラが話題なのでさわってみました。 国内で話題になっている元の記事は「webpack時代の終わりとparcel時代のはじまり 」。 React との組み合わせで記事を書かれています。

個人的にはRiot.js が好みなので、Riot.jsとの組み合わせで触ってみました。 尚、webpackは挫折したため比較できません。

Parcel/Riot.jsのインストール

npmを使ってインストールします。

1
$ npm install -g parcel-bundler riot

source code

ディレクトリ構造

以下の様なディレクトリ構造だとします。 なお、練習用のため、動作確認に関係ない部分は適当に削っています。

src/
|- index.html
|- index.js
|- package.json
|- app/
|  |- App.tag

index.html

1
2
3
4
5
6
7
8
<!doctype html>
<html lang="ja">
  <head></head>
  <body>
    <App></App>
    <script src="index.js"></script>
  </body>
</html>

index.js

1
2
3
4
import riot from 'riot'
import './app/tags'

riot.mount('App')

App.tag

1
2
3
4
5
6
7
<App>
  <h1>Hello, parcel world!</h1>

  <script>
  import riot from 'riot' 
  </script>
</App>

package.json

package.jsonnpm init -yで作成しました。

compile/bundle & run

1
2
$ riot app/ app/tags.js
$ parcel index.html

上記のコマンドで http://localhost:1234 でホットリロードのサーバが動作します。 最終的な成果物を作る場合は parcel build index.htmlとすれば良いようです。

しかし、riot.jsのコンパイルはparcelの前段で別途行っているため、tagファイルの変更はwatchされません。riotコマンドに-wオプションをつけることでウォッチできますが、そのままだと二つのコマンドを別々の端末で開くなどする必要があり、若干面倒です。 package.jsonscriptsに以下の三つのコマンドを追加します。

1
2
3
4
5
{
"watch": "npm run watch:riot & npm run watch:parcel",
"watch:riot": "riot -w app/ app/tags.js",
"watch:parcel": "parcel index.html"
}

追加したら、以下のコマンドを実行します。

1
$ npm run watch

これでコマンド一つでホットリロードの開発サーバを動作させることができます。