ありふれた内容なので、主に自分の勉強目的&備忘録です。
↓↓より詳しくまとめてくださっている記事がありました↓↓
- 動作環境
- macOS 11.6.8
- node v16.27.0
- npm 8.15.0
初期化作業
ディレクトリ作成&移動
新規の空ディレクトリ(typescript_sample
とする)を作成し、ディレクトリに移動します。
mkdir typescript_sample
cd typescript_sample
その下にsrc
ディレクトリ、dist
ディレクトリを作成します
mkdir dist
mkdir src
package.jsonの生成
以下コマンドを実行します。
npm init -y
Typescriptのインストール
npm install --save-dev typescript
lite-serverのインストール
npm install --save-dev lite-server
package.jsonの編集
package.json
{
"name": "typescript_sample",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
- "test": "echo \"Error: no test specified\" && exit 1"
+ "test": "echo \"Error: no test specified\" && exit 1",
+ "start": "lite-server"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"lite-server": "^2.6.1",
"typescript": "^4.8.3"
}
}
.gitignoreの作成
以下の内容で.gitignore
を作成します。
.gitignore
node_modules
dist
tsconfig.jsonの生成・編集
以下コマンドを実行すると、tsconfig.json
が生成されます。
npx tsc --init
以下のように編集します。
tsconfig.json
{
"compilerOptions": {
/* Basic Options */
//中略
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
- // "rootDir": "./", /* Specify the root folder within your source files. */
+ "rootDir": "./src", /* Specify the root folder within your source files. */
//中略
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
- // "outDir": "./", /* Specify an output folder for all emitted files. */
+ "outDir": "./dist", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
//中略
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
+ "exclude": ["node_modules"]
}
index.htmlの作成
以下の内容で作成します。
./index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>typescript_sample</title>
<script src="dist/index.js" defer></script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
index.tsの作成
以下の内容でsrc
ディレクトリの下に作成します。
src/index.ts
console.log("Hello")
ディレクトリ構成
ここまで行うと以下のようなディレクトリ構成になっていると思います。
動かす
コンパイラをウォッチモードで起動
npx tsc -w
lite-serverを起動
新規ターミナルを開いて、以下で起動します。
npm start
動作確認
自動でブラウザが起動し、ページが表示されます。
ブラウザの開発者ツールを開くと、コンソールに文字(Hello
)が出力されており、問題なく動作しています。
以上。
本記事のコードはGithubに上げています。
その他
自動フォーマット(VSCode)
-
VSCodeの拡張機能であるPrettierをインストール