0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【TypeScript】開発環境の準備方法メモ

Last updated at Posted at 2023-05-09

はじめに

どうも、TypeScript勉強中の👶です。
理解を深めるために日々の学びを記事にしています。
初心者の記事なので言い回しや記載に誤りがあるかも知れませんが、暖かく見守っていただけると幸いです。
(よろしければ間違いをコメントいただけると学び、励みになります!)

学んだこと

・TypeScriptの開発環境の準備方法

前提

node.jsインストールは完了しているところからのスタートです。

ディレクトリ作成

$ mkdir ディレクトリ名
$ cd ディレクトリ名

npmインストール

$ npm init --yes

package.jsonが作成されるので、下記内容を変更

"main":"index.js",
↓↓↓
"main":"index.js",
"type":"module",

Typescriptと@types/nodeのインストール

$ npm install --save-dev typescript @types/node

(補足)gitをcloneしてきた場合

gitをcloneしてきた場合、package.jsonやpackage.lock.jsonはあるが、module_nodeはない(gitignore設定のため)状態なので、下記を実行して生成する。

$ npm install

tsconfig.jsonの準備

$ npx tsc --init

tsconfig.jsonはTypeScriptコンパイラの設定ファイルです。

tsconfig.jsonを編集します。

{
    "compilerOptions":{
        // トランスパイルの程度(デフォルト: "es2016")
        "target": "es2020",
        
        // moduleコンパイラ(デフォルト: "commonjs")
        "module":"esnext"
        
        // moduleResolutionコンパイラオプションをnode(コメント解除)する
        "moduleResolution":"node"
        
        // outDirコンパイラオプション(コンパイラ出力ディレクトリを指定)
        // コメントアウトを解除して出力ディレクトリを変更
        
        "outDir": "./dist"
    },
            
    // includeオプション (コンパイル対象の指定)
    "include":["./src/**/*.ts"]
}

ファイル作成

srcディレクトリを作成し、その中にTypeScriptを記載するファイル(.ts)を作成します。

コンパイル実行

$ npx tsc

実行すると、なんと摩訶不思議!
distファイルにコンパイル後のコード(.js)が出力されます。

コードをNode.jsで実行する

動くのはコンパイル後のファイルです。

$ node dist/index.js
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?