3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[React]絶対パスでimportできるようにする with vscode and eslint

Last updated at Posted at 2018-05-24

やりたいこと

  • CreateReactAppで作ったプロジェクトでimportのパスを絶対パスで書きたい
  • vscodeの補完やeslintも今まで通り動いてほしい
// bad
import SomeComponent from '../../components/SomeComponent';

// good
import SomeComponent from 'src/components/SomeComponent';

React

  • NODE_PATHという環境変数にrootとなるパスを指定するとできる

  • 実行時に指定するパターン

    NODE_PATH=. yarn start
    
  • .envファイルに書くパターン

    .env
    NODE_PATH=.
    

ESLint

  • 動くようになってもこのままだとESLintが警告を出してくる
  • ESLintのconfigに設定を追加することで対処できる
.eslintrc.yaml
settings:
  import/resolver:
    node:
      moduleDirectory:
      - node_modules
      - /
.eslintrc.json
{
  "settings": {
    "import/resolver": {
      "node": {
        "moduleDirectory": ["node_modules", "/"]
      }
    }
  }
}

VSCode

  • 最後に補完が効くようにVSCodeに設定を入れる
  • jsconfig.jsonというファイルを作って以下のように書けばOK
jsconfig.json
{
  "compilerOptions": {
    "target": "es2015",
    "baseUrl": "./"
  }
}
3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?