はじめに
TypeScriptの環境構築をしたので、メモ代わりに書いていきます。
Node.jsのインストール
はじめに、TypeScriptを書いていく上で、必要になるNode.jsをインストールしていきます。
Node.jsを使用する理由は、JavaScriptやTypeScriptで作られたライブラリやコマンドなどを使うための、パッケージマネージャを備えている「npm」を使えるようにするためです。
私は、以下のページで、Node.jsの導入はv18のバージョンをインストールしました。
https://nodejs.org/ja
環境構築
まずは適当なディレクトリを作成します。今回は「test」というディレクトリの中に環境構築していきます。
まずは以下のコマンドでディレクトリ内で、npmを使用できるようにします。
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.
ここで以下のような出力がされて、「パッケージの名前を決めろ」とと言われます。
package name: (test)
今回は以下のような名前にして、Enterを押します。
package name: (test) typescript-test
次に以下のような表示が出てきますが、全てEnterで大丈夫です。
package name: (test) typescript-test
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
全てEnterを押すと以下のような出力があるので、Enterで大丈夫です。
About to write to /Users/fukushimaryouhei/Desktop/test/package.json:
{
"name": "typescript-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes)
この時点で、Node.jsのプロジェクトが作成されるので、以下のコマンドでTypeScriptのコンパイラをインストールします。
$ npm install -D typescript
added 1 package, and audited 2 packages in 1s
found 0 vulnerabilities
インストールができたら、コンパイラのバージョンを確認します。
npx tsc -v
Version 5.0.2
次に、TypeScriptの詳細設定をします。
$ npx tsc --init --rootDir src --outDir lib --esModuleInterop --resolveJsonModule --lib es6,dom --module commonjs
Created a new tsconfig.json with:
TS
target: es2016
module: commonjs
lib: es6,dom
outDir: lib
rootDir: src
strict: true
esModuleInterop: true
skipLibCheck: true
forceConsistentCasingInFileNames: true
You can learn more at https://aka.ms/tsconfig
そうすると、ディレクトリ内にtsconfig.jsonファイルが作成されます。
ディレクトリ内が以下のようになっていると思います。
% ls
node_modules package-lock.json package.json tsconfig.json
実際に動かしてみる
実際にTypeScriptを使って、出力をしてみましょう。
ルートディレクトリにsrcディレクトリを作成して、その中にtest.tsファイルを作成しましょう。
コードはこんな感じにします。
const hello: string = "hello";
const world: string = "world";
console.log(`${hello} ${world}`);
コードを作成したので、コンパイルして実行します。
1.コンパイル
npx tsc -p .
2.実行
% node lib/test.js
hello world
hello worldが出力されました!
以上になります。