概要
みなさんこんにちはcandleです。
今回はAtom + eslintの導入をしてみましょう。
以前書いたemacsより圧倒的に環境作りが簡単です。
近年はeslintが主流になってきて、Atomに限らずあらゆる場面で使われるようになってきました。
前提
nodeがインストールされている
Atomがインストールされている
eslintのインストール
はじめに、eslintをインストールします。
私はeslintをMac PCのグローバルにインストールします。
-gフラグを立てることで、PC全てで使えるようになります。
npm install -g eslint
続いて、eslintのreactプラグインをインストールします。
npm install -g eslint-plugin-react
同じく-gフラグをつけることで、グローバルに使用できるようになります。
インストールが終わったらeslintと打ち込んでコマンドが使えるか確認します。
eslint
Atomのeslintプラグインをインストールする
Atomを開いて、上のメニューバーの「Atom」から「Preferences…」を選び
左のメニューバーから「Install」を押し、検索ボックスに「eslint」と打ち込み、エンターを押します。
候補の中の「linter-eslint」をインストールします。
インストール中、依存するパッケージのインストールの確認が出来ます。
全て許可しましょう。
eslintの設定
eslintの設定ファイルはホームディレクトリにファイルを設置します。
ちなみに、検証していませんが、各Reac projectに設置することもできると思います。
ホームディレクトリに.eslintrcファイルを作成します。
touch ~/.eslintrc
私は、どの様にeslintの構文チェック設定を書けば良いか分からないので、ほぼコピペです。
参考にしたサイト
https://github.com/yannickcr/eslint-plugin-react/issues/18#issuecomment-80754101
このように書きます。
{ "env" : { "es6": true }, "plugins": [ "react" ], "parserOptions": { "ecmaFeatures": { "jsx": true, "modules": true }, "sourceType": "module" }, "rules": { "strict": 0, "no-throw-literal": 1, "quotes": [1, "single"], "react/no-multi-comp": 1, "react/prop-types": 1, "react/display-name": 1, "react/wrap-multilines": 1, "react/self-closing-comp": 1, "react/no-did-mount-set-state": 1, "react/no-did-update-set-state": 1, "react/jsx-uses-react": 1, "react/jsx-uses-vars": 2, "react/react-in-jsx-scope": 1 } }
1つ注意事項があります。
"parserOptions": { "ecmaFeatures": { "jsx": true, "modules": true }, "sourceType": "module" },
の部分はeslintのバージョンによって書き方が違うらしく、もしも、うまくいか無い人はこのように書き換えてください。
"ecmaFeatures": { "jsx": true, "modules": true }, "parserOptions": { "sourceType": "module" },
このgithubのissueに書いてあります。
https://github.com/yannickcr/eslint-plugin-react/issues/447
私が調べた範囲で解説します。
“es6”: true
},
はes6で書いていることの宣言。
“react”
],
冒頭でインストールしたeslintのreactプラグインを使うことの宣言
“ecmaFeatures”: {
“jsx”: true,
“modules”: true
},
“sourceType”: “module”
},
jsxを使うことの宣言。
“sourceType”: “module”はこれが無いとreact componentのimport文で警告がでる。
rulesはeslintのルール
これらのルールの詳しい内容は公式サイトを参考にしてください。
http://eslint.org/docs/rules/
これで設定が終わりました。
テストファイルを作成する
構文チェックを行うサンプルファイルを作成します。
場所はとりあえずどこでも良いので、デスクトップにでも作ります。
touch ~/Desktop/App.js
中身を以下のようにします。
import React from 'react'; class App extends React.Component{ constructor(){ super(); this.state = { txt: 'this is the state text' } } update(e){ this.setState({ txt: e.target.value }) } render(){ return( <div> <p>Text: {this.state.txt}</p> <input name="" type="text" onChange={this.update.bind(this)} /> </div> ) } } const Person = (props) => <h4>{props.name}</h4> export default App;
2箇所の警告を出していれば成功です。
警告の場所は const Personの所です。
警告文を読むには
フッターの所の2と表示してある警告の場所をクリックするか
コードの警告が出ている場所にマウスホーバーすれば見れます。
まとめ
Reactはとにかく書き方が豊富です。eslintを使うことで、ファイルによって書き方が違うみたいなことをなくすことができます。