0
2

More than 1 year has passed since last update.

【TypeScript】TypeScriptの第一歩

Posted at

概要

TypeScriptをチャレンジ、最初の第一歩を踏み出したい方向けの記事となります。

環境・前提

PC:MacBook Pro
使用エディタ:VSCode

npmというパッケージ管理システムを利用するため、Node.jsが必要になります。
こちらのダウンロードページ』から(LTS※推奨版を)ダウンロード、インストールしてください。

★Node.jsインストールすると「npm」というコマンドが使用できるようになります。

# 執筆時点の各バージョン
node -v
v16.14.2

npm -v
8.5.0

手順

プロジェクトの初期化

まずは、Mac標準のターミナル開き、以下のコマンドを入力していきます。

# 任意のディレクトリ内で作業ディレクトリを作成 & 移動
mkdir sample_frontend
cd sample_frontend
# VSCodeを開く(VSCodeが開いたら「command + jキー」を押し、ターミナルを表示してください)
code .
# VSCodeのターミナル(もしくは先ほどまでのターミナル)で
# 初期化(続けて質問されるがここでは全てEnter ※最後は「yes & Enter」)
npm init
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 init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.

# ↓ここから私たちが入力する(今回は基本的にEnter ※後で書き換えることも可能)
package name: (sample_frontend) 
version: (1.0.0) 
description: 
entry point: (index.js) 
test command: 
git repository: 
keywords: 
author: 
license: (ISC) 
About to write to /Users/andotaishi/dev/sample_frontend/package.json:

# ↓の内容が後述のpackage.jsonに記載されている
{
  "name": "sample_frontend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this OK? (yes) yes

作業ディレクトリ内に「package.json」が作成されたことを確認する。

TypeScriptを導入

ターミナルに戻り、引き続き実行。

# -g オプションをつけてグローバルに「typescript」パッケージをインストール
npm install -g typescript
# 「hello.ts」というファイルをVSCodeで新規作成するか以下コマンドで作成
touch hello.ts

作成した「hello.ts」に以下を記載。

hello.ts
const message: string = 'Hello World';

console.log(message);

ターミナルに戻り、以下のtscコマンドでJavaScriptへ変換。

# 「tsc」コマンドは、typescriptパッケージをインストールすると使用可能になる
tsc hello.ts

作業ディレクトリ内に「hello.js」というコンパイルされたjsファイルが作成されました。
(※ファイルの中身も比較してみてください)

今後は、tsconfig.jsonというコンパイル時のオプション設定ファイルを作成したり、ESLintの導入など...チャレンジしてみましょう!!

0
2
2

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
0
2