Motomichi Works Blog

モトミチワークスブログです。その日学習したことについて書いている日記みたいなものです。

webpackを使ってES2015、Vue.jsのビルド環境を構築する

参考にさせて頂いたページ

webpackのすごく基本

webpack で始めるイマドキのフロントエンド開発 - Qiita

以前書いたReact.jsの記事

webpackを使ってES2015、React.jsのビルド環境を構築する - Motomichi Works Blog

Vue.jsでの記述例について

vue.js + webpack の紹介(その2) - Qiita

https://github.com/vuejs/vue-webpack-example/blob/master/src/views/a/index.js

プロジェクトディレクトリを作成

webpack-vue-sampleディレクトリを作成した。

グローバルにインストール

npm install -g webpack babel

プロジェクトにインストール

まずpackage.jsonを作成する。

npm init

webpack-vue-sammpleディレクトリで以下のコマンドを実行した。

npm install --save-dev webpack vue html-loader babel-core babel-loader babel-preset-es2015

今回webpack-vue-sample内に作成するディレクトリ構造とファイル

以下のディレクトリやファイルを手順に沿って作成していきます。

  • index.html
  • package.json
  • webpack.config.js
  • node-modules/*
  • src/main.js
  • src/vue-materials/sample.js
  • src/vue-materials/template-hoge.html
  • src/vue-materials/template-foo.html
  • result/bundle.js

webpack.config.jsの作成とその記述内容

webpack-vue-sampleディレクトリに作成した。記述内容は以下の通り。

const path = require('path');

module.exports = {
  entry: './src/main.js',
  output: {
    path: `${__dirname}/result`,
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        loader: 'babel-loader',
        exclude: /node_modules/,
        test: /\.js[x]?$/,
        query: {
            cacheDirectory: true,
            presets: ['es2015']
        }
      },
      {
        test: /\.html$/,
        loader: "html-loader"
      }
    ]
  },
  resolve: {
    modules: [path.join(__dirname, 'src'), 'node_modules'],
    extensions: ['.js']
  },
  plugins: []
}

./src/main.jsの作成とその記述内容

require('./vue-materials/sample');

./src/vue-materials/sample.jsの作成とその記述内容

templateをrequire()するところ以外は普通のVue.jsの記述と同じで、以下の通り。

var Vue = require('vue');

var app = new Vue({
  el : '#app',
  components: {
    'my-hoge': {
      template: require('./template-hoge.html')
    },
    'my-foo': {
      template: require('./template-foo.html')
    }
  }
});

./src/vue-materials/template-hoge.htmlの作成とその記述内容

<div>テンプレート hoge</div>

./src/vue-materials/template-foo.htmlの作成とその記述内容

<div>テンプレート foo</div>

index.htmlの作成とその記述内容

webpack-vue-sampleディレクトリに作成した。
webページ作成用の普通のhtmlです。コンパイルされたbundle.jsを読み込みます。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<title>vue-tutorial</title>
</head>
<body>

<div id="app">
  <my-hoge></my-hoge>
  <my-foo></my-foo>
</div>

<script type="text/javascript" src="result/bundle.js"></script>
</body>
</html>

watchしてコンパイルしてみる

webpack -d --watch

src/vue-materials/template-hoge.htmlなどを編集して保存すると、result/bundle.jsが生成される。

ページを見てみる

index.htmlをブラウザで開いてみる。

確認できた。