Reactでの../../../インポートはもう不要

Reactでの../../../インポートはもう不要

Nilanth

2021年8月15日に投稿、2023年4月22日に更新

Create React Appでサードパーティのパッケージなしで絶対パスインポートを設定する手順。

../../../../somecomponentsのようにコンポーネントをインポートしていますか?その場合は絶対パスインポートに更新すべきです。

絶対パスインポートのメリット

  1. 既存のコードを他のコンポーネントにインポートする際、変更を加えることなく移動できます。
  2. インポートパスを使用して、コンポーネントが実際にどこに配置されているかがすぐに識別できます。
  3. よりクリーンなコードになります。
  4. 書きやすくなります。

絶対パスインポートの設定

絶対パスインポートをサポートするためには、ルートディレクトリにjsconfig.jsonという名前のファイルを作成し、下記のコードを追加してください。

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

この設定を完了したら、以下のコンポーネント内の相対インポートを絶対パスインポートに変換しましょう。

import React from 'react';
import Button from '../../components/Button';
import { red } from '../../utils/constants/colors';

function DangerButton(){
  return <Button color={red} />;
}

export default DangerButton;

上記のインポートは、以下のように変更されます。

import React from 'react';
import Button from 'components/Button';
import { red } from 'utils/constants/colors';

function DangerButton(){
  return <Button color={red} />;
}

export default DangerButton;

これでインポートがクリーンで分かりやすくなりました。

JET Brains IDEでの設定

  • JET BrainsのIDEであるWebStorm、PhpStorm、RubyMineなどでは、絶対パスインポートをサポートするためにいくつか追加設定が必要です。

srcフォルダを右クリックし、Mark Directory asを選択してからResource Rootをクリックします。

Resource Root

  • 次にPreferences -> Editor -> Code Style -> JavaScript -> Importsへ進み、Use paths relative to the project, resource or source rootsをチェックしてからApplyをクリックします。

ide-resource

VS Code

VS Codeでは変更する必要はありません。jsconfig.jsonファイルから設定が自動的にインポートされます。

リソース

  1. VS Code jsconfig.json
  2. JET Brains CodeStyle

結論

絶対パスインポートは、コンポーネントをより読みやすく、クリーンにします。この情報が役立つことを願っています。読んでいただき、ありがとうございました。

Twitterで更に情報を得る。

eBook

Debugging ReactJS Issues with ChatGPT: 50 Essential Tips and Examples

ReactJS Optimization Techniques and Development Resources

その他のブログ

  1. Laravel Sanctum Authentication for React App Using Breeze
  2. Twitter Followers Tracker using Next.js, NextAuth and TailwindCSS
  3. Don't Optimize Your React App, Use Preact Instead
  4. Build a Portfolio Using Next.js, Tailwind, and Vercel with Dark Mode Support
  5. 10 React Packages with 1K UI Components
  6. Redux Toolkit - The Standard Way to Write Redux
  7. 5 Packages to Optimize and Speed Up Your React App During Development
  8. How To Use Axios in an Optimized and Scalable Way With React
  9. 15 Custom Hooks to Make your React Component Lightweight
  10. 10 Ways to Host Your React App For Free
  11. How to Secure JWT in a Single-Page Application

    こちらの記事はdev.toの良い記事を日本人向けに翻訳しています。
    https://dev.to/nilanth/no-more-import-in-react-2mbo