LoginSignup
14
10

More than 3 years have passed since last update.

TypeScript導入編

Last updated at Posted at 2019-09-15

Vue.jsで開発したアプリケーションにTypeScriptを導入したので、その備忘録を。

TypeScriptをinstall

globalでinstallする記事がありましたが、ここはプロジェクトごとにinstallさせました。

$ yarn add -D typescript

tsconfig.jsonを作成と設定

$ tsc --init

設定項目

  • コンパイラが出力するJavaScriptのバージョンはes5を対象とする
  • ブラウザ向けのプログラムなのでDOMを指定
  • source mapをtrueにする
  • 厳格モードをtrue(必須)
  • 対象ファイルをsrcディレクトリのtsファイルにする
  • node_moduleの中のtsファイルは対象外
  • angularのテストファイルは対象外
tsconfig.json
"compilerOptions": {
  "target": "es5",
  "module": "es2015",
  "lib": ["DOM", "ES2015"],
  "sourceMap": true,
  "strict": true,  
  "moduleResolution": "node",
},
"include": [
  "src/**/*"
],
"exclude": [
  "node_modules",
  "**/*.spec.ts"
]

webpackでtsファイルをバンドル対象にする

webpackでバンドルするときにtsファイルも対象にしたいので指定

  • ts-loaderをinstall
  • webpackでtsファイルをバンドル対象にする
  • ファイルをimportするときに拡張子を指定しなくてもいいようにextensionsを指定
$ yarn add -D ts-loader
webpack.config.js
module: {
  rules: [
    {
      test: /\.ts$/,
      use: 'ts-loader',
    },
  ]
}
resolve: {
  extensions: ['.ts'],
},

npmのタスクランナーでwatchさせる

package.json
"scripts": {
  "start": "concurrently \"webpack-dev-server --config webpack.dev.js\" \"yarn run tsc -- -w\"",
  "tsc": "tsc -p ./"
}

設定時のエラー

コンパイルしたときに下記のエラーが出た場合

moduleResolutionの設定

File change detected. Starting incremental compilation...
[1] 
[1] node_modules/@types/babel__core/index.d.ts(13,20): error TS2307: Cannot find module '@babel/types'.
[1] node_modules/@types/babel__core/index.d.ts(14,31): error TS2307: Cannot find module '@babel/parser'.
[1] node_modules/@types/babel__generator/index.d.ts(9,20): error TS2307: Cannot find module '@babel/types'.
[1] node_modules/@types/babel__template/index.d.ts(9,31): error TS2307: Cannot find module '@babel/parser'.
[1] node_modules/@types/babel__template/index.d.ts(10,54): error TS2307: Cannot find module '@babel/types'.
[1] node_modules/@types/babel__traverse/index.d.ts(10,20): error TS2307: Cannot find module '@babel/types'.

tsconfig.jsonmoduleResolutionnodeにすると解決

tsconfig.json
"compilerOptions": {
  "moduleResolution": "node",

moduleの設定

Uncaught ReferenceError: exports is not defined
Object.defineProperty(exports, "__esModule", { value: true });

tsconfig.jsonmodulees2015にすると解決

tsconfig.json
"compilerOptions": {
  "module": "es2015",

参考サイト

14
10
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
14
10