28
19

More than 5 years have passed since last update.

【2019年7月版】TypeScript はじめの一歩

Last updated at Posted at 2019-07-07

TypeScript を使用したプロジェクトの始め方

TypeScript での開発の始め方がフレームワークやそのバージョンによって色々ありますので現時点での設定手順を棚卸いたしました。

バージョンについて

執筆において使用した各種コマンド・モジュールのバージョンを列挙しておきます。

  • node: 10.15.3
  • npm: 6.9.0
  • yarn: 1.16.0
  • typescript: 3.5.2
  • nuxt: 2.8.1
  • react: 16.8.6
  • react-scripts: 3.0.1
  • angular: 7.2.0
  • angular-cli: 7.3.8
  • deno: 0.10.0

1. npm

以下は npm を使用してシンプルに Typescript を開始する手順です。

1-1. プロジェクト作成

npm initコマンドで適当なプロジェクトを作成いたします。

$ mkdir npm_typescript_sample
$ cd npm_typescript_sample
$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
...

npm の質問には適宜、回答しておきます。

1-2. TypeScriptをプロジェクトに追加

$ npm i -D typescript
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN typescript_install@1.0.0 No description
npm WARN typescript_install@1.0.0 No repository field.

+ typescript@3.5.2
added 1 package from 1 contributor and audited 1 package in 981.308s
found 0 vulnerabilities

1-3. TypeScript 初期設定

tsc --init コマンドでtsconfig.jsonを生成します。

$ npx tsc --init
message TS6071: Successfully created a tsconfig.json file.

tsconfigはとりあえず初期設定のままで動作確認をいたします。

1-4. 起動スクリプトを追記

package.json に以下のように起動スクリプトを追記しておきます。

package.json
{
...
  "scripts": {
    "start": "tsc -p . && node .",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
...
}

1-5. 起動

適当に以下のような 'index.ts' ファイルを作成いたします。

$ touch index.ts
index.ts
console.log("hello world.");

もう、全然 TypeScriptじゃなくてすいません・・・
以下のコマンドで起動できます。

$ npm start
...

hello world.

TypeScript、起動できました!

1-6. js 生成先の変更

デフォルトでは index.ts と同じディレクトリにindex.jsが生成されます。
捨てスクリプトを書く分には問題ありませんがちょっと規模の大きいプロジェクトになると気になってくると思います。
その場合は tsから生成されるjsの出力先を tsconfig.json にて変更できます。

tsconfig.json
{  "compilerOptions": {
  ...
 "outDir": "./dist",
 ...
}}

起動スクリプトも以下のようにdist以下を参照するように修正しておきます。

package.json
...
    "start": "tsc -p . && node dist/.",
...

2. yarn

以下は yarn を使用してシンプルに TypeScript を開始する手順です。
基本的な手順は npm と一緒です。

2-1. プロジェクト作成

$ mkdir yarn_typescript_sample
$ cd yran_typescript_sample
$ yarn init
yarn init v1.16.0
question name (yarn_typescript_sample):
question version (1.0.0):
question description:
question entry point (index.js):
question repository url:
question author:
question license (MIT):
question private:
success Saved package.json
✨  Done in 8.95s.

2-2. TypeScriptをプロジェクトに追加

$ yarn add -D typescript
yarn add v1.16.0
info No lockfile found.
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 🔨  Building fresh packages...
success Saved lockfile.
success Saved 1 new dependency.
info Direct dependencies
└─ typescript@3.5.2
info All dependencies
└─ typescript@3.5.2
✨  Done in 5.67s.

2-3. TypeScript 初期設定

tsc --init コマンドでtsconfig.jsonを生成します。

$ yarn run tsc --init
...
message TS6071: Successfully created a tsconfig.json file.
✨  Done in 1.02s.

先ほどと同様にtsconfigはとりあえず初期設定のままで動作確認をいたします。

2-4. 起動スクリプトを追記

package.json に以下のように起動スクリプトを追記しておきます。

package.json
{
...
  "version": "1.0.0",
  "scripts": {
    "start": "tsc -p . && node ."
  },
  "main": "index.js",
...
}

2-5. 起動

適当に以下のような 'index.ts' ファイルを作成いたします。

$ touch index.ts
index.ts
console.log("hello world.");

以下のコマンドで起動できます。

$ yarn start
yarn run v1.16.0
$ tsc -p . && node .
hello world.
✨  Done in 6.16s.

TypeScript、起動できました!

3. Nuxt.js

3-1. スターターキットを使用してプロジェクトを作成

以下は Nuxt.js のスターターキット create-nuxt-appを使用する手順です。

$ yarn create nuxt-app nuxt_typescript_app
yarn create v1.16.0
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 🔨  Building fresh packages...

success Installed "create-nuxt-app@2.8.0" with binaries:
      - create-nuxt-app
create-nuxt-app v2.8.0
✨  Generating Nuxt.js project in /Users/xxx/nuxt_typescript_app
? Project name nuxt_typescript_app
? Project description My superior Nuxt.js project
? Author name Yoshinori Koide
? Choose the package manager Yarn
? Choose UI framework Bootstrap Vue
...
✨  Done in 13.89s.

🎉  Successfully created project nuxt_typescript_app

  To get started:

        cd nuxt_typescript_app
        yarn dev

  To build & start for production:

        cd nuxt_typescript_app
        yarn build
        yarn start

  To test:

        cd nuxt_typescript_app
        yarn test

✨  Done in 354.85s.
$ yarn dev
yarn run v1.16.0
$ cross-env NODE_ENV=development nodemon server/index.js --watch server
[nodemon] 1.19.1
...

上記で http://localhost:3000 に開発サイトが立ち上がります。

ここから先の手順はちょと長いので以下のサイトをご覧ください。すいません。。。

3-2. スクラッチで構築

スターターキットを使用せずに、まっさらな Next.js プロジェクトに TypeScript を追加する手順です。

3-2-1. プロジェクトの作成

まずは新規プロジェクト作成してnuxt.jsを追加します。
ここでは yarn を使用しますが npm でも同様です。

$ mkdir nuxt_typescript_manual_sample
$ cd nuxt_typescript_manual_sample
$ yarn init
yarn init v1.16.0
question name (nuxt_typescript_manual_sample):
question version (1.0.0):
question description:
question entry point (index.js):
question repository url:
question author:
question license (MIT):
question private:
success Saved package.json
✨  Done in 5.43s.
$ yarn add nuxt
yarn add v1.16.0
info No lockfile found.
[1/4] 🔍  Resolving packages...
warning nuxt > @nuxt/webpack > postcss-preset-env > postcss-color-functional-notation > postcss-values-parser > flatten@1.0.2: I wrote this module a very long time ago; you should use something else.
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 🔨  Building fresh packages...
...
├─ yallist@3.0.3
└─ yargs@3.32.0
✨  Done in 91.48s.

3-2-2. TypeScript 追加

続いて TypeScript サポートを追加します。

$ yarn add -D @nuxt/typescript
yarn add v1.16.0
[1/4] 🔍  Resolving packages...
warning @nuxt/typescript > @types/chokidar@2.1.3: This is a stub types definition. chokidar provides its own type definitions, so you do not need this installed.
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 🔨  Building fresh packages...
...
├─ typescript@3.5.2
└─ worker-rpc@0.1.1
✨  Done in 32.68s.
$ yarn add ts-node
yarn add v1.16.0
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
warning " > ts-node@8.3.0" has unmet peer dependency "typescript@>=2.0".
[4/4] 🔨  Building fresh packages...
success Saved lockfile.
success Saved 4 new dependencies.
info Direct dependencies
└─ ts-node@8.3.0
info All dependencies
├─ arg@4.1.0
├─ make-error@1.3.5
├─ ts-node@8.3.0
└─ yn@3.1.0
✨  Done in 22.41s.
$ touch tsconfig.json
$ touch nuxt.config.ts

tscongig.json は nuxt 初回起動時に宜しくやってくれますので空白のままでOKです。
nuxt.config.ts は以下の内容で保存しておきます。

nuxt.config.ts
import NuxtConfiguration from '@nuxt/config'

const config: NuxtConfiguration = {
  // タイプするか `Ctrl + Space` を押すとオートコンプリートできます
}

export default config

3-2-3. 起動スクリプトの追加

nuxt コマンドを叩くだけの dev スクリプトを追加します。

package.json
...
  "version": "1.0.0",
  "scripts": {
    "dev": "nuxt"
  },
  "main": "index.js",
...

3-2-4. 初期ページの作成

index ページを作成します。

$ mkdir pages
$ touch pages/index.vue

内容は以下のようにしておきます。

index.vue
<template>
  <h1>Hello world!</h1>
</template>

3-2-5. 起動

あとは dev スクリプトを呼び出すだけです。

$ yarn dev
yarn run v1.16.0
$ nuxt
ℹ Generating /tsconfig.json                                                                                                    22:16:41

   ╭─────────────────────────────────────────────╮
   │                                             │
   │   Nuxt.js v2.8.1                            │
   │   Running in development mode (universal)   │
   │   TypeScript support is enabled             │
   │                                             │
   │   Listening on: http://localhost:3000/      │
   │                                             │
   ╰─────────────────────────────────────────────╯
...

http://localhost:3000 にてhello worldが表示されます。
上記では yarn を使用しておりますが、npm run dev でも同じです。

4. React

React にて TypeScript を有効にする手順です。
すっぴんのReactにTypeScriptを組み込んでいくのは非常に手間なので最初からスターターキットを使用します。

4-1. npm(npx) を使用してプロジェクト作成

npm を使用する場合、以下の手順です。

$ npx create-react-app react-typescript-npm-app --typescript
npx: 91個のパッケージを19.153秒でインストールしました。
...
Success! Created react-typescript-npm-app at /Users/xxx/react-typescript-npm-app
Inside that directory, you can run several commands:

  yarn start
    Starts the development server.

  yarn build
    Bundles the app into static files for production.

  yarn test
    Starts the test runner.

  yarn eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd react-typescript-npm-app
  yarn start

Happy hacking!
$ cd react-typescript-npm-app
$ npm start
...
Starting the development server...
...

で、http://lcoalhost:3000 にて開発サイトが立ち上がります。便利。
(なんかyarnがインストールされているせいか?yarnでのコマンドが表示されておりますが・・・)

4-2. yarn を使用してプロジェクト作成

yarn を使用する場合、以下の手順です。

$ yarn create react-app react-typescript-yarn-app --typescript
...
$ cd react-typescript-yarn-app
$ yarn start
...
Starting the development server...
...

で、http://lcoalhost:3000 にて開発サイトが立ち上がります。楽チン。

5. Angular でプロジェクト作成

Angular はそもそも TypeScript を使用しますので、普通にプロジェクトを作成すればOKです。

$ ng n ang-sample-app
...
$ cd ang-sample-app
$ ng serve

上記のコマンドで http://localhost:4200 にて開発サイトが立ち上がります。

番外編:deno

TypeScript をそのまま動かす(というかjsの変換を宜しくやってくれる)エンジンとして deno があります。
既存のjsライブラリは一切使えませんが、ネイティヴTypeScriptのビッグウェイヴにライドオンしたいという方は deno もおすすめ(?)です。

最新版をインストールしてサンプルを動かしてみる手順は以下です。

$ curl -fsSL https://deno.land/x/install/install.sh | sh
...
$ deno version
deno: 0.10.0
v8: 7.7.37
typescript: 3.5.1
$ deno https://deno.land/welcome.ts
Download https://deno.land/welcome.ts
Compile https://deno.land/welcome.ts
Welcome to Deno 🦕

デノザウラー?が表示されましたね。・・・はい。(個人的には deno 推しです。)

さいごに

npm i -g typescript はやめよう!

参考サイト

28
19
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
28
19