Parcel で VueのSFC(単一ファイルコンポーネント)をビルドしてみる


これはなに

話題の📦 ParcelでVueの単一ファイルコンポーネント(SFC; Single File Components)をビルドしてみた記事です。Parcelの基本的な情報は他記事を参照してください。

サンプルコードは corocn/parcel-vue-sfc-sample に置きました。

環境構築

yarn or npmでサクッと入れちゃいます。

parcel単体では、VueのSFCが使えないので、parcel-plugin-vueが必要です。

yarn add parcel-bundler parcel-plugin-vue vue babel-preset-env

コード

Hello Worldしてみます。
各種ファイルを用意します。全部ルートにべた置きです。
コンポーネントは.vue形式でないと読み込んでくれませんので注意。

index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Sample</title>
</head>
<body>
  <div id="app"></div>
  <script src="./index.js"></script>
</body>
</html>
index.js
import Vue from 'vue';
import Hello from './Hello.vue'

const app = new Vue(Hello);
app.$mount('#app');
Hello.vue
<template>
  <div>{{greeting}} World!</div>
</template>

<script>
  module.exports = {
    data: function() {
      return {
        greeting: 'Hello'
      }
    },
    mounted: function() {
      console.log('mounted!')
    }
  }
</script>

<style>
  div {
    color: red;
  }
</style>

<style scoped>
  div {
    font-size: 32px;
  }
</style>
.babelrc
{
  "presets": ["env"]
}

実行

yarn parcel index.html

http://localhost:1234/ で確認しましょう。

scoped cssも効いてますね

parcel-plugin-vue

まだ不安定なので、Productionでの使用はオススメできないとのことです。今後に期待。

Stability: 1 - Experimental This feature is still under active development and subject to non-backwards compatible changes, or even removal, in any future version. Use of the feature is not recommended in production environments.

感想

驚くほど簡単に動く。ぱぱっと動かしたい時に便利だなぁ、と思いました。