LoginSignup
17
10

More than 3 years have passed since last update.

Parcel + Vue.js で素早く環境を作る。

Last updated at Posted at 2019-08-09

はじめに

Vue.jsで素早くLPを作らなければならなくなった。
ビルドするのにwebpackやgulpなどがあるが、もっと手っ取り早くできる方法はないかと調べたところ、parcelを発見した。

Parcel公式サイト
https://ja.parceljs.org/

準備

簡単に動作確認できるように最低限の準備

ディレクトリを作ってnpm init

$ mkdir hoge
$ cd hoge
$ npm init

最低限のファイルを作る

hoge
├── src
│   ├── index.html
│   ├── index.js
│   └── App.vue
└── package.json
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>

  <div id="app"></div>
  <script src="index.js"></script>

</body>
</html>
index.js
import Vue from 'vue';
import App from './App.vue';

new Vue({
    el: '#app',
    render:h => h(App)
});
App.vue
<template>
  <p>{{ message }}</p>
</template>

<script>
  module.exports = {
    data: function () {
      return {
        message: 'Hello'
      }
    }
  }
</script>

<style lang="scss">
p {
  font-size: 2em;
  text-align: center;
}
</style>

scssの必要はないけど、ちゃんと認識されるよってわかるようにつけてみた

npm install

vueparcelをインストール

$ npm install --save-dev parcel-bundler vue

buildする

$ npx parcel build src/index.html

--out-dirで出力場所を指定できる(指定しないとdistに出力される)

これだけで、ビルドができた。

serverを立ち上げてみる

$ npx parcel start src/index.html

2020/02/28 修正
@saba_uni_toro_ さんありがとうございます

startはサーバーが立ち上がってリアルタイムで変更を反映してくれる優れもの。
開発中はとりあえずstartしとけばおk

scriptに追記する

使いやすいようにpackage.jsonscriptに追記

package.json
{
  "name": "test-parcel",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "parcel build src/index.html --out-dir public", // 追加
    "start": "parcel src/index.html", // 追加
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "parcel": "^1.12.3",
    "vue": "^2.6.10"
  },
  "devDependencies": {
    "@vue/component-compiler-utils": "^3.0.0",
    "sass": "^1.22.9",
    "vue-template-compiler": "^2.6.10"
  }
}

この設定をいれておけばnpm run startnpm run buildで完結するので良き。

便利なプラグイン

  • parcel-plugin-static-files-copy
    プロジェクト直下(package.jsonがあるとこ)にstaticディレクトリを作って、
    ファイルを放り込むと、buildするときにstatic内のものをコピーしてくれる。
    cp static/* publicみたいな感じ。

まとめ

実質、parcelインストールしてbuildすれば終わり。
めちゃめちゃ楽だった。

懸念点

  • buildするたびにファイルが増える現象がある。
    下記のコマンドをpackage.jsonのbuildの先頭に書いて一度全削除してbuildし直してもらうことで対応はできる。
ls -ad public/* | grep -v -E '^\\.$|^\\.\\.$' | xargs rm -rf
  • 出力されたpublicを見ると全て展開されてごちゃごちゃになっていた。
    まとめる方法ないかなぁ...
17
10
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
10