7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Parcelで作るSPAじゃないVue.js環境構築

Last updated at Posted at 2019-08-21

Parcelを使うと簡単にフロントエンドの開発環境構築ができますが、複数ファイルのエントリファイルに対応しているのを知ったので試してみたいと思います。

Parcelのインストール

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

複数のhtmlファイルを作成

一つ目の画面作成

まずIndexページ作成を作成します。

src/index.html

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

エントリファイルを作成します。

src/index.js

import Vue from 'vue/dist/vue.esm.js';
import App from './App.vue';

Vue.component('app', App);

new Vue({ el: '#app' });

Indexページで使用するVueコンポーネントを作成します。

<template>
  <div>
    {{ message }}
  </div>
</template>

<style>
</style>

<script>
  export default {
    name: 'App',
    data() {
      return({
        message: 'Index page',
      });
    },
  }
</script>

二つ目の画面作成

今回はSPAじゃないので複数画面があり、各画面に対してエントリファイルを読み込む形にします。

次に同じようにAboutページを作成します。

src/about.html

<html>
  <body>
    <div id="app">
      <about></about>
    </div>
    <script src="./about.js"></script>
  </body>
</html>

src/about.js

import Vue from 'vue/dist/vue.esm.js';
import About from './About.vue';

Vue.component('about', About);

new Vue({ el: '#app' });

src/About.vue

<template>
  <div>
    {{ message }}
  </div>
</template>

<style>
</style>

<script>
  export default {
    name: 'About',
    data() {
      return({
        message: 'About page',
      });
    },
  }
</script>

Parcelコマンドの設定

package.jsonに複数ファイルをwatchモードで実行できるよう設定します。

"scripts": {
    "start": "parcel src/*.html",
    "watch": "parcel watch src/*.html"
},

実行してみる

まずParcelをwatchモードで実行します。

$ npm run watch

すると最初はParcelが必要な依存関係をインストールしてくれて、ビルドが走ります。

ビルド後は対象のファイル変更を検知してHot Reloadが効いてくれます。

ビルドファイルはデフォルトで/distへ出力されます。

watchモードではwebサーバーが起動しないので、http-serverを使ってアプリを動かします。

$ npx http-server dist -p 8000

起動したら、localhost:8000localhost:8000/about にアクセスしてみるとVueが動いているのがわかります。

まとめ

Parcelを使うことでVueの開発環境が驚くほど簡単に構築できました。

複数ファイルをサポートしているのも嬉しいですね!

参考

7
4
0

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
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?