LoginSignup
2
1

More than 5 years have passed since last update.

[React Native]importを絶対パスで書く

Last updated at Posted at 2018-06-03

やりたいこと

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

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

ReactNative

  • package.jsonのnameの値がrootパスになる
package.json
{
  "name": "sample",
  ...
}
src/components/Foo.js
export default ...
src/components/Bar.js
import Foo from 'sample/src/components/Foo';

ESLint

  • 動くようになってもこのままだとESLintが警告を出してくる
  • ESLintのプラグインを一つ追加する
yarn add -D eslint-import-resolver-reactnative
  • .eslintrcに設定を追加
.eslintrc.yaml
settings:
  import/resolver: reactnative
.eslintrc.json
{
  "settings": {
    "import/resolver": "reactnative"
  }
}

VSCode

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