LoginSignup
5
7

More than 5 years have passed since last update.

TypeScriptのtsconfig.jsonをあれこれしてみた その1

Last updated at Posted at 2019-01-04

ぼやき

フロントエンドはカオスだなー
カオスだけどついていきたいなーと頑張っているけどやっぱりカオスだなー

React + webpack + TypeScriptであれこれしているんですが
webpack.config.jsで数多のローダーを組み合わせたり
tsconfig.jsonの設定をどうにかしないといけなかったりと奔走しているうちに
ちょっとまずTypeScriptのtsconfigについて見てみようとなった次第です。

環境

  • Mac OS Mojave v10.14.2
  • node.js v10.9.0
  • npm v6.2.0
  • yarn v1.9.4
  • Visual Studio Code v1.30.1

 最低限の環境を準備

  • とりあえず適当な作業ディレクトリを作ってそこに移動(以下、このディレクトリをrootと表記)
  • 以下のコマンドを実行
yarn init
yarn add -D typescript

rootの中はこうなってるはず。

root
 ┣━ node_modules
 ┣━ package.json
 ┗━ yarn.lock

typescript使えるようになったかな?

以下のコマンドを打ってtypescript compilerのバージョンが表示されれば成功してる。

npx tsc -v
> Version 3.2.2

最低限のコードを書いて試してみる

root直下にindex.tsを作成:

index.ts
console.log("Hello World!");

index.tsをコンパイルする。

npx tsc index.ts

root直下にindex.jsが出来上がる。

index.js
console.log("Hello World!");

JavaScriptで書けるコードしか書いてないので当たり前だが中身は何も変わらず。

コンパイルで出来たindex.jsを実行してみよう:

node index.js
> Hello World!

当然の結果ですね。

ディレクトリ構成を変えたい。

こうしたい:

root
 ┣━ node_modules
 ┣━ src           ← typescriptのコードを入れるところ
 ┃   ┗━ index.ts
 ┣━ build         ← コンパイルした結果を入れるところ
 ┃   ┗━ index.js
 ┣━ package.json
 ┗━ yarn.lock
  • root/srcディレクトリを作ってindex.tsをそこに移動する
  • 以下のコマンドを実行する。
npx tsc ./src/index.ts --outDir ./build
  • --outDirオプションを指定して出力先を指定。

まぁとりあえず現時点ではこれでよしとしよう。

外部ファイルを読み込みたい。

とりあえずsrc/util.tsを作る:

util.ts
function hoge() {
  console.log("This is Util!");
}

index.tsutil.tsを読み込む:

index.ts
import util from './util';
console.log("Hello World!");

コンパイルする:

npx tsc ./src/index.ts --outDir ./build
> src/index.ts:1:18 - error TS2306: File '/Users/nekonecode/work/lab/ts/src/util.ts' is not a module.

util.jsmoduleじゃない!とおこです。
このモジュールってのが割とカオスってるなと、昔は思いました。(今もカオスではあると思う)

util.tsをmoduleにする。

util.ts
export function hoge() {
  console.log("This is Util!");
}

exportをつけるだけです。
exportは外で使えるようにする目印のようなもので、これを付けないと外から使えない。

再びコンパイルします:

npx tsc ./src/index.ts --outDir ./build
> src/index.ts:1:8 - error TS1192: Module '"/Users/nekonecode/work/lab/ts/src/util"' has no default export.

default exportがねぇぞ!と再び怒っています。

これの解決策はいくつかございますが、今回はindex.tsの方でどうにかしましょう。

importの書き方 その1

index.ts
import * as util from './util';
console.log("Hello World!");

util.tsを全てimportし、それらをutilという名前で取り扱うという書き方。

ついでなのでutil.hoge()を実行する処理も書いておきましょう。

index.ts
import * as util from './util';
console.log("Hello World!");
util.hoge();

これで無事にコンパイルできました。

コンパイルされた結果のindex.jsを実行してみる。

node ./build/index.js
> Hello World!
> This is Util!

いけました。

さて、tsconfig.jsonについてまだ触れていませんが
何やら長くなってしまったので続きはまた今度。

お疲れ様でした。

追記

TypeScriptのtsconfig.jsonをあれこれしてみた その2

5
7
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
5
7