owned mediaウェブ制作に役立つコンテンツを発信中!

Vue.js(Composition API)+TypeScriptの環境でVuex・Vue Router・axiosを使ってみる#1:環境構築

最終更新日: Update!!
今回はVue.jsの3系とTypeScriptでシンプルなアプリケーション開発を例に、VuexとVue Router、axiosを使うまでをまとめてみたいと思います。Vuexでアプリケーションの状態管理を、Vue Routerでルーティングの設定を、axiosで非同期のHTTP通信というこれらのライブラリを使うことでSPA形式のアプリケーションが手軽に作成することができます。第一回目の今回はwebpackをベースにした開発環境を進めていきます。   また、過去記事でも関連した内容をあげていますので、そちらもよければご参考ください。 ・Vue.js 3系の導入とComposition APIを試してみる ・webpack&TypeScriptのプロジェクトでVue.jsを使える開発環境を構築してみる ・Vue-CLIのプロジェクトでaxiosを使ってAPIや外部リソースからのデータを取得する ・Vue CLIとVuexでアプリケーションの状態変化を扱う ・Vue CLIとVue RouterでミニマムなSPAを最短で構築する   今回の開発環境ですが、下記のような構成を想定したものになります。コンパイル前のソースファイルと、出力後の公開用ファイルでそれぞれディレクトリを分けており、各種設定ファイルが含まれます。「types」ディレクトリには、後で追加していく各モジュール用の型定義ファイルが格納されます。
┣ dist
  ┣ index.html
    ┗ assets
      ┗ js
        ┗ main.min.js
┣ src
  ┗ ts
    ┣ main.ts
    ┗ vue
      ┗ app.vue
┣ .eslintrc.js
┣ .tsconfig.json
┣ .tsconfig..eslint.json
┣ package.json
┣ webpack.config.js
┣ node_modules
┣ ......
┗ types
  ┗ vue.d.ts
  普段プロジェクトで使っているものをベースにしています。実際にはこれに加えて、PugやSassのコンパイル、画像の圧縮やファイルリネームなどいろんな機能を盛り込んだものを使っています(ソースはこちら)が、今回はTypeScriptのコンパイルやVueファイルのビルド、ローカルサーバーでのブラウザ自動更新など必要最小限の内容を紹介しています。下記のモジュールをそれぞれインストールしておきます。 【package.json】※一部抜粋
{
  ......
  "devDependencies": {
    "@babel/core": "^7.14.0",
    "@babel/plugin-transform-runtime": "^7.18.2",
    "@babel/preset-env": "^7.14.1",
    "@typescript-eslint/eslint-plugin": "^4.24.0",
    "@typescript-eslint/parser": "^4.24.0",
    "@vue/compiler-sfc": "^3.2.33",
    "babel-loader": "^8.2.2",
    "browser-sync": "^2.27.9",
    "browser-sync-webpack-plugin": "^2.3.0",
    "eslint": "^7.26.0",
    "eslint-plugin-vue": "^9.3.0",
    "eslint-webpack-plugin": "^2.5.4",
    "style-loader": "^2.0.0",
    "ts-loader": "^9.1.1",
    "typescript": "^4.2.4",
    "vue-class-component": "^7.2.6",
    "vue-loader": "^17.0.0",
    "vue-style-loader": "^4.1.3",
    "webpack": "^5.36.2",
    "webpack-cli": "^4.6.0"
  },
  "dependencies": {
    "@babel/runtime": "^7.18.3",
    "jquery": "^3.6.0",
    "vue": "^3.2.31"
  }
}
  webpackでのPugやSassコンパイル、画像圧縮などの環境構築については過去記事でもまとめておりますので、合わせてご覧ください。 ・webpackでSassのコンパイル環境の作成と外部CSSへの書き出しをできるようにする ・webpackでPostCSSを使ったベンダープレフィックスの追加やCSSのminifyを行う ・webpackでPugのコンパイル環境を作成してみる ・webpackで画像圧縮を自動化する環境を構築する ・webpackでStylelintが使える環境を構築してみる   モジュールのインストールができたら、各種設定ファイルを用意していきます。こちらも目的に合わせて適宜内容を設定していきます。まずはESLintの設定ファイルです。 【.eslintrc.js】
module.exports = {
  root: true,
  env: {
    es6: true,
    node: true,
  },
  parser: '@typescript-eslint/parser',
  parserOptions: {
    sourceType: 'module',
    ecmaVersion: 2019,
    tsconfigRootDir: __dirname,
    project: [ 
      './tsconfig.eslint.json'
    ]
  },
  plugins: [
    '@typescript-eslint',
  ],
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:@typescript-eslint/recommended-requiring-type-checking',
  ],
  rules: {
    'no-console': 'warn',
    'no-extra-semi': 'warn',
    'no-undef': 'warn',
    'quotes': [
      'warn', 'single'
    ],
    'space-before-blocks': [
      'warn', { 
        'functions': 'always' 
      }
    ],
    '@typescript-eslint/no-unsafe-call': 'warn',
    '@typescript-eslint/no-unsafe-member-access': 'warn',
    '@typescript-eslint/no-unsafe-return': 'warn',
    '@typescript-eslint/no-unsafe-assignment': 'warn',
    '@typescript-eslint/no-explicit-any': 'warn'
  },
};
  続いてTypeScriptの設定ファイルも同じように用意していきます。合わせてLintの対象も設定しておきます。 【.tsconfig.json】
{
  "files": [
    "types/vue.d.ts"
  ],
  "include": [
    "src/ts/**/*"
  ],
  "exclude": [
    "node_modules"
  ],
  "compilerOptions": {
    "incremental": true, 
    "target": "es5",
    "module": "es2015", 
    "sourceMap": true, 
    "removeComments": true,
    "strict": true,
    "allowSyntheticDefaultImports": true,
    "lib": [
      "dom",
      "es2020"
    ],
    "experimentalDecorators": true,
    "esModuleInterop": true ,
    "moduleResolution": "node"
  }
}
  【.tsconfig.eslint.json】
{
  "extends": "./tsconfig.json",
  "include": [
    "src/**/*.ts",
    "src/**/*.vue",
    "types/**/*.ts",
    ".eslintrc.js",
    "webpack.config.js"
  ],
  "exclude": [
    "node_modules",
    "dist" 
  ]
}
  ESLintの設定ファイルの後は、型定義ファイルを作成していきます。後ほど別ファイルを追加していくことになるので、ディレクトリにまとめておくのが良いですね。まずは.vueの拡張子を持つ単一コンポーネントファイルの型を定義しておきます。 【types/vue.d.ts】
declare module '*.vue' {
  import { ComponentOptions } from 'vue'
  const component: ComponentOptions;
  export default component
}
  最後にwebpackの設定ファイルになります。エントリーポイントはソースディレクトリ側にあるスクリプトファイルになり、その他各種ファイルをバンドルしていくビルドになります。ここでは合わせてBabelを使ったトランスパイルも実行しています。後はBrowsersyncを使ったローカルサーバーの起動と、ブラウザの自動リロードも追加しています。その他環境に必要な機能があれば適宜追加していきます。 【webpack.config.js】
const path = require('path');
const ESLintPlugin = require('eslint-webpack-plugin');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const { VueLoaderPlugin } = require('vue-loader');

module.exports = {
  mode: 'development',
  devtool: 'source-map',
  entry: `${path.resolve(__dirname, 'src')}/ts/main.ts`,
  output: {
    path: `${path.resolve(__dirname, 'dist')}/assets`,
    filename: 'js/main.min.js'
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: {
          loader: 'ts-loader',
          options: {
            appendTsSuffixTo: [/\.vue$/]
          }
        }
      },
      {
        test: /\.js$/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: [ 
                [
                  '@babel/preset-env',
                  {
                    'targets': {
                      'node': true
                    }
                  },
                ],
              ]
            }
          }
        ]
      },
      {
        test: /\.vue$/,
        use: 'vue-loader'
      },
      { 
        test: /\.css$/, 
        use: [ 
          'style-loader', 
          { 
            loader: 'css-loader', 
            options: { url: false, } 
          }
        ]
      },
    ]
  },
  resolve: {
    alias: { 'vue$': 'vue/dist/vue.esm-bundler.js' },
    extensions: [ '.ts', '.js', '.vue', '.json' ]
  },
  plugins: [
    new ESLintPlugin({
      extensions: [ '.ts', '.js' ],
      exclude: 'node_modules'
    }),
    new BrowserSyncPlugin({
      host: 'localhost',
      port: 2000,
      server: { baseDir: path.resolve(__dirname, 'dist') }
    }),
    new VueLoaderPlugin(),
  ],
  target: [ 'web', 'es5' ],
  performance: {
    maxEntrypointSize: 512000,
    maxAssetSize: 512000
  }
};
  webpackの設定ファイルが作成できれば、実際にビルドするソースコードを書いていきます。今回のエントリーポイントになるスクリプトファイルにて、Vue.js本体を読み込み「createApp()」でVue.jsのインスタンスを作成します。そして「component()」で各種コンポーネントを使えるようにしておき、最後にVue.jsを使う対象となる要素にマウントします。 【main.ts】
import { createApp } from 'vue';
import App from './vue/app.vue';

const app = createApp({});
app.component('app', App)
  .mount('#app');
  最後にテスト用のコンポーネントを用意し、ページ上に表示されるか試してみます。 【vue/app.vue】
<template>
  <h1>{{ data.message }}</h1>
</template>

<script lang="ts">
  import { defineComponent, reactive } from 'vue';

  interface dataInterface {
    message: string
  }

  export default defineComponent({
    setup() {
      const data:dataInterface = reactive({ 
        message: 'Hello world' 
      });
      return {
        data
      }
    }
  });
</script>
  HTML側で上記のコンポーネントを設置しておき、最後にビルドをするとコンポーネントに出力した内容がページ上にされます。先ほど設定したようにマウントした要素内に配置するように注意します。 【index.html】
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Sample APP</title>
  </head>
  <body>
    <div id="app">
      <app />
    </div>
    <script src="assets/js/main.min.js"></script>
  </body>
</html>
 
  ここまでの流れでひとまずはVue.jsとTypeScriptのビルド環境が用意できました。引き続き、必要なコンポーネントや処理を追加していきますが、こちらについては次回記事にて詳しくまとめてみたいと思います。
  • はてなブックマーク
  • Pocket
  • Linkedin
  • Feedly

この記事を書いた人

Twitter

sponserd

    keyword search

    recent posts

    • Twitter
    • Github
    contact usscroll to top
      • Facebook
      • Twitter
      • Github
      • Instagram