Mokelab Blog

TypeScript を導入しよう

前回は webpack を導入し、 npm run build でビルドできるようにしました。今回はこのプロセスに Typescript を加えてみます。

TypeScriptとは

TypeScriptとはプログラミング言語の1つで、コンパイルすると JavaScript が結果として出てきます。コンパイルという手順があるため、変数名の Typo や、型の不一致などを実行時ではなくコンパイル時に検出できるようになります。このような JavaScript に変換する言語を altJS と呼んだりもします。

TypeScript をプロジェクトに追加する

TypeScript 本体はnpm でインストールできます。開発時にしか使用しないので --save-devをつけておきましょう。

$ npm install --save-dev typescript
(中略)
+ typescript@3.6.3
added 1 package from 1 contributor and audited 5287 packages in 4.13s
found 0 vulnerabilities

TypeScript 公式サイトでは、tsc コマンドを使えるようにするため、-g をつけてインストールする方法が紹介されています。今回は webpack 経由で使うので、-gはつけません。

tsconfig.json を作る

TypeScript はビルド時の設定を tsconfig.json というファイルに記述します。このファイルは tsc コマンドで生成できるので、次のコマンドで生成します。

$ ./node_modules/.bin/tsc --init
message TS6071: Successfully created a tsconfig.json file.

中身は次のようになっています。

{
  "compilerOptions": {
    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
  }
}

次の 2 点だけ、変更しておきます。

webpack.config.js に設定を追加する

webpack 経由で TypeScript のコンパイルを行いたいので、 webpack.config.js を編集します。

module.exports = {
    mode: "development",

    entry: "./src/main.ts",

    module: {
        rules: [
            {
                test: /\.ts$/,
                use: "ts-loader"
            }
        ]
    },

    resolve: {
        extensions: [".js", ".ts"]
    }
};

変更点は次の 3 箇所です。

ruleの部分は、「ファイル名がこれにマッチしたら、これを使うよ」というルールを記述します。ここでは TypeScript のソースファイルである .tsファイルに対し、ts-loaderを使う設定を追加しています。 resolveの部分はモジュール解決時、どの順序で調べるかを記述します。TypeScript で記述されたモジュールを使えるようにするため、ts.jsの後に追加します。

ts-loader を追加する

webpack でts-loaderを使う設定を書いたので、インストールしておきます。 こちらも製品のコードに使うものではないので、--save-devをつけておきます。

$ npm install --save-dev ts-loader

+ ts-loader@6.2.0
added 8 packages from 20 contributors and audited 5322 packages in 3.879s
found 0 vulnerabilities

ビルドする

srcの中にmain.tsを用意しておきます。TypeScript のソースなので、型をちゃんとつけて次のように書いてみます。

// main.ts
const msg: string = "Hello TypeScript world!"
console.log(msg);

ここまで準備できたら、ビルドしてみましょう。

$ npm run build

> demoapp@1.0.0 build /(中略)/demoapp
> webpack

Hash: a694812d32481bef2cf1
Version: webpack 4.41.0
Time: 806ms
Built at: 2019/10/07 0:00:00
  Asset      Size  Chunks             Chunk Names
main.js  3.87 KiB    main  [emitted]  main
Entrypoint main = main.js
[./src/main.ts] 80 bytes {main} [built]

赤文字な ERROR といった文字列が見えなければ、成功です。

まとめ

webpack に TypeScript に関する設定を追加し、ビルドできるようにするための手順を説明しました。TypeScript のコンパイル時にいろいろ確認できる機能はアプリ開発において非常に強力なので、導入しておきましょう。

本サイトではサービス向上のため、Google Analyticsを導入しています。分析にはCookieを利用しています。