awesome-typescript-loader,tslintからts-loader,eslintに乗り換える
概要
GWなのでちょいちょい噂になってた以下2点対応しようと思う
- awesome-typescript-loader -> ts-loaderに変更
- もうawesomeなスピードじゃないし、ソースの更新も止まってるらしい
- tslint->eslintに変更
- typescriptチームが正式にeslintにするって言ったとかどうとか
ts-loader対応
ts-loaderインストール
$ npm install --save-dev ts-loader
ts-loaderを使用する設定
webpack.config.jsで 「use: 'awesome-typescript-loader',」を「use: 'ts-loader',」に変更するだけで行けた。
webpack.config.js
module: { // ファイルタイプに対するloaderの設定 rules: [ { test: /\.tsx?$/, use: 'ts-loader', },
eslint対応
eslintとeslint-loaderのインストール
linterであるeslint自体と、webpackから対象ファイルを読み込むためのeslint-loaderをインストール
npm install --save-dev eslint eslint-loader
eslint-loaderの設定
webpack.config.jsで以下の通りruleを指定
enforce:pre
でts-loaderが走り出す前に実行test: /\.(js|ts|jsx|tsx)$/,
で対象になりそうな拡張子全部指定exclude: /node_modules/,
でnode_modulesは対象外にする
webpack.config.js
module: { // ファイルタイプに対するloaderの設定 rules: [ { enforce: "pre", test: /\.(js|ts|jsx|tsx)$/, exclude: /node_modules/, loader: "eslint-loader", }
eslint自体の設定
まずは最小の設定
こんな感じで最小設定してみる
"root": true
で親階層の設定を見に行かない(同階層の設定ファイルを優先)"env": {}
でglobalな変数をeslintに理解させる"es6": true,
でes6形式に記述してもeslintに怒られなくなる"browser": true
でdocument,consoleなど記載しても怒られない
"extends": ["eslint:recommended",
でおすすめlinter設定"parserOptions": {"sourceType": "module"}
でES6を有効化
.eslintrc
{ "root": true, "env": { "es6": true, "browser": true }, "extends": [ "eslint:recommended" ], "parserOptions": { "sourceType": "module" } }
webpack実行すると10:5 error Parsing error: Unexpected token <
が出てくる。
ReactのFragment Shortcut<>
のとこで怒られた
$ # package.jsonの以下script実行 $ # "scripts": { "build": "webpack", $ npm run build 10:5 error Parsing error: Unexpected token <
Reactエラーが出ないように対応させる
@typescript-eslint/eslint-plugin
でeslintをReactにも対応させられそう。
でもこれを動かすには@typescript-eslint/parser
もインストールする必要があるらしい。
@typescript-eslint/typescript-estree
を入れるとパースするときにAST(Abstract Syntax Tree)として取り扱えるらしい。なんのこっちゃ。とりあえず入れとく。
$ npm install --save-dev @typescript-eslint/parser @typescript-eslint/typescript-estree @typescript-eslint/eslint-plugin
extendsに"plugin:react/recommended"
を追加する。
pluginsに指定する方式もあるらしいがこれでいこう。
{ "root": true, "env": { "es6": true, "browser": true }, "extends": [ "eslint:recommended", "plugin:react/recommended" ], "parserOptions": { "sourceType": "module" } }
webpack実行すると11:14 error Parsing error: Unexpected token =
が出てくる。
jsxで<div id=""
ってしてるだけなのになんか怒られる。
$ npm run build 11:14 error Parsing error: Unexpected token =
eslintでtypescriptもlintしてくれるように設定
そもそも、eslintがTypeScriptを理解させるための設定入れてないよな。
typescriptのparserを入れ込む
{ "root": true, "env": { "es6": true, "browser": true }, "extends": [ "eslint:recommended", "plugin:react/recommended" ], "parser": "@typescript-eslint/parser", "parserOptions": { "sourceType": "module" } }
webpack実行するとついにエラー消えたしちゃんとjsファイル出力されてる!
まとめ
今回仕事で初めてフロントにも取り組んだけど。
ほんと変化激しい。ちょっと放置してるとduplicateになってるし。
置いてかれないように見つけたらすぐ対応するようにしよう。