よしたく blog

ほぼ週刊で記事を書いています

Parcelをさわってみた

この記事は、yoshitaku_jpの1人 Advent Calendar 2018 - Adventar の7日目の記事です。

気になっていたバンドルツールのParcelを使ってみました。

parceljs.org

比較として並行してWebpackも触りましたが、設定ファイルを書かないお手軽さに完全に負けてしまい、Parcelばかり触ってしまいます。設定ファイルを用いて、開発と本番での使い分けができるのがWebpackのいいところで、Parcelはお手軽に試せるのがいいところでしょうか。

試してみたこと

基本的なことばかりですが、並べておきます。

  • インストール
  • CLI
    • コマンド
    • オプション
      • 出力先の変更
      • 出力ファイル名の変更
      • ブラウザ起動

インストール

グローバルな環境にインストールしています。 このタイミングでのバージョンは、1.10.3 でした。

npm install -g parcel-bundler

yoshitaku$ parcel -V
1.10.3

CLI

コマンド

準備

node.jsを使う前での準備です。実行済みでしたら必要ありません。

npm init -y

今回使用するindex.html です。

<html>
<body>
  <script src="./index.js"></script>
</body>
</html>

今回使用するindex.js です。

console.log('hello world')

ここまでの作業で、下記のディレクトリになっているはずです。

yoshitaku$ tree
.
├── index.html
├── index.js
└── package.json

ここから各コマンドを見ていきます。

serve

parcel index.html コマンドで開発用サーバーが起動します。dist ディレクトリが作成され配下にファイルが出力されます。デフォルトのポートは 1234です。ファイルを変更してもすぐに反映されます。 f:id:yoshitaku_jp:20181206074134p:plain

build

parcel build index.html コマンドでビルドができます。 dist ディレクトリが作成され配下にファイルが出力されます。

f:id:yoshitaku_jp:20181206074522p:plain

watch

parcel watch index.html コマンドで開発用のサーバを立ち上げずにファイルの変更を検知してビルドしてくれます。

f:id:yoshitaku_jp:20181206075200p:plain

オプション

出力先の変更

-d オプションで、出力先を変更できます。 例 parcel build index.html -d build/output

yoshitaku$ tree
.
├── index.html
├── index.js
└── package.json

0 directories, 3 files
yoshitakuMBA:parcel yoshitaku$ parcel build index.html -d build/
✨  Built in 325ms.

build/parcel.cb1a8511.js     1.08 KB    12ms
build/parcel.cb1a8511.map      190 B     6ms
build/index.html                73 B     6ms
yoshitakuMBA:parcel yoshitaku$ tree
.
├── build
│   ├── index.html
│   ├── parcel.cb1a8511.js
│   └── parcel.cb1a8511.map
├── index.html
├── index.js
└── package.json

1 directory, 6 files

出力ファイル名の変更

--out-file オプションで、出力ファイルの名前を変更することができます。

parcel build index.html --out-file output2.html

yoshitaku$ tree
.
├── index.html
├── index.js
└── package.json

0 directories, 3 files
yoshitakuMBA:parcel yoshitaku$ parcel build index.html --out-file output2.html
✨  Built in 315ms.

dist/parcel.cb1a8511.js     1.08 KB    14ms
dist/parcel.cb1a8511.map      190 B     7ms
dist/output2.html              73 B     6ms
yoshitakuMBA:parcel yoshitaku$ tree
.
├── dist
│   ├── output2.html
│   ├── parcel.cb1a8511.js
│   └── parcel.cb1a8511.map
├── index.html
├── index.js
└── package.json

1 directory, 6 files

ブラウザ起動

parcel index.html --open serve のときに使える限定のオプションです。

指定しておくと開発サーバが起動したタイミングでブラウザが起動してくれます。

感想

  • 基本的なコマンドをさわったが、非常に手軽だった。なにより早くビルドされるのが嬉しい。
  • 今度も軽いプロダクトを作るときはparcelを使っていきたい
  • Webpackも比較対象としてさわっておきたい