Vue.js + TypeScriptの始め方
7月から新しいチームに参画しました。Nuxt.js+TypeScriptを使ったプロジェクトで、技術的な難易度は高くないとのことなんですが、Nuxt.jsは会社が推しているフロントエンド技術でもあるようなので、これから学習していこうと思っています。まずは何事も基本から、ということで今回はNuxt.jsの前にVue.s+TypeScriptのコードを書いていくための下準備を行なっていきます。
手順などは公式ドキュメントに従います。
v3.vuejs.org
Vue CLIのインストール
まずはVue CLIをインストールしていきます。業務ではyarnを使っているみたいなので今回はyarnを使います。
yarn global add @vue/cli
以下のコマンドを実行してバージョンが表示されればOKです
vue --version
プロジェクト作成
次にプロジェクトを作ります。下記のコマンドはhello-world-appという名前のプロジェクトを作るコマンドです。
vue create hello-world-app
コマンドを実行するとターミナルが以下のような表示になります。
? Please pick a preset: (Use arrow keys) ❯ Default ([Vue 2] babel, eslint) Default (Vue 3) ([Vue 3] babel, eslint) Manually select features
vue.jsをそのまま使うのであればVue2かVue3で問題ありませんが、今回はTypeScriptを使うので「Manually select features」を選択します。
次は以下のような表示になります。
? Please pick a preset: Manually select features ? Check the features needed for your project: (Press <space> to select, <a> to t oggle all, <i> to invert selection) ❯◉ Choose Vue version ◉ Babel ◯ TypeScript ◯ Progressive Web App (PWA) Support ◯ Router ◯ Vuex ◯ CSS Pre-processors ◉ Linter / Formatter ◯ Unit Testing ◯ E2E Testing
TypeScriptを使用するので、TypeScriptを選択します。選択するには矢印キーで移動してスペースキーを押します。
下記のようにTypeScript横の丸が塗りつぶされた状態になっていればOKです。
? Please pick a preset: Manually select features ? Check the features needed for your project: ◉ Choose Vue version ◉ Babel ❯◉ TypeScript ◯ Progressive Web App (PWA) Support ◯ Router ◯ Vuex ◯ CSS Pre-processors ◉ Linter / Formatter ◯ Unit Testing ◯ E2E Testing
エンターキーを押して次に進みます。
あとはお好みで問題ありませんが、参考に僕が選んだ結果を以下に載せておきます。
? Please pick a preset: Manually select features ? Check the features needed for your project: Choose Vue version, Babel, TS, Linter ? Choose a version of Vue.js that you want to start the project with 2.x ? Use class-style component syntax? No ? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? Yes ? Pick a linter / formatter config: Basic ? Pick additional lint features: Lint on save ? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files ? Save this as a preset for future projects? (y/N)No
正常にプロジェクトが作成されたら以下のような出力がされているはずです。
🎉 Successfully created project hello-world-app. 👉 Get started with the following commands: $ cd hello-world-app $ yarn serve
次は指示に従ってアプリケーションを動かしてみます。
アプリケーションの実行
以下のコマンドを実行します。
cd hello-world-app yarn serve
ブラウザからhttp://localhost:8081/にアクセスするとVue.js + TypeScriptのWelcomeページが表示されます。
Hello Worldする
僕はどんな言語や技術でもHello Worldと出力することから始めることにしているので、今回もやっていきます。
./src/App.vueを以下のように編集します。
<template> <div id="app"> <h1>Hello World!</h1> </div> </template>
これでhttp://localhost:8081/にアクセスしたら「Hello World!」と出力されているはずです。
まとめ
おつかれさまでした。とはいっても今回は本当に初歩的なことをしているだけですけどね。次からはVue.jsやTypeScriptの構文についてのポストをしていきたいと思います。