Reactでの../../../インポートはもう不要
2021年8月15日に投稿、2023年4月22日に更新
Create React Appでサードパーティのパッケージなしで絶対パスインポートを設定する手順。
../../../../somecomponents
のようにコンポーネントをインポートしていますか?その場合は絶対パスインポートに更新すべきです。
絶対パスインポートのメリット
- 既存のコードを他のコンポーネントにインポートする際、変更を加えることなく移動できます。
- インポートパスを使用して、コンポーネントが実際にどこに配置されているかがすぐに識別できます。
- よりクリーンなコードになります。
- 書きやすくなります。
絶対パスインポートの設定
絶対パスインポートをサポートするためには、ルートディレクトリに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
をクリックします。
- 次にPreferences -> Editor -> Code Style -> JavaScript -> Importsへ進み、Use paths relative to the project, resource or source rootsをチェックしてからApplyをクリックします。
VS Code
VS Codeでは変更する必要はありません。jsconfig.json
ファイルから設定が自動的にインポートされます。
リソース
結論
絶対パスインポートは、コンポーネントをより読みやすく、クリーンにします。この情報が役立つことを願っています。読んでいただき、ありがとうございました。
Twitterで更に情報を得る。
eBook
Debugging ReactJS Issues with ChatGPT: 50 Essential Tips and Examples
ReactJS Optimization Techniques and Development Resources
その他のブログ
- Laravel Sanctum Authentication for React App Using Breeze
- Twitter Followers Tracker using Next.js, NextAuth and TailwindCSS
- Don't Optimize Your React App, Use Preact Instead
- Build a Portfolio Using Next.js, Tailwind, and Vercel with Dark Mode Support
- 10 React Packages with 1K UI Components
- Redux Toolkit - The Standard Way to Write Redux
- 5 Packages to Optimize and Speed Up Your React App During Development
- How To Use Axios in an Optimized and Scalable Way With React
- 15 Custom Hooks to Make your React Component Lightweight
- 10 Ways to Host Your React App For Free
- How to Secure JWT in a Single-Page Application
こちらの記事はdev.toの良い記事を日本人向けに翻訳しています。
https://dev.to/nilanth/no-more-import-in-react-2mbo