1
1

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 1 year has passed since last update.

これを読むとコードがめっちゃ読みやすくなる! Next.js(React)とTypeScriptでパスのaliasを設定(importエイリアス)について

Last updated at Posted at 2023-10-23

この記事を書いている時のバージョン

Next.jsの13の時に書いてあります。

% npx next -v

Next.js v13.5.3
npm notice 
npm notice New major version of npm available! 8.19.2 -> 10.2.1
npm notice Changelog: https://github.com/npm/cli/releases/tag/v10.2.1
npm notice Run npm install -g npm@10.2.1 to update!
npm notice 

どういう場面で使ったか

componentsフォルダの中にusersフォルダを作って、Header.tsxを作成した。
そのデータをインポートするために以下のコードを書いた。

import { Header} from "../components/users/Header";

しかし、importエイリアスを使うように言われて調べて実装することにしました。

どう書き換えた?

公式ドキュメントを調べてみて以下のように記述を書き換えました。

import { TableHeader } from "@/components/users/Header";

"../"@に書き換えました。
そしてtsconfig.jsonを以下のように記載しました。

tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/components/*": ["components/*"]
    },
#省略
}

このように書き換えました。もし

import { useAuth } from "@/contexts/authContext";

とかならこのようにtsconfig.jsonに付け足します。

tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/components/*": ["components/*"],
      "@/contexts/*": ["contexts/*"]
    },
#省略
}

importエイリアスのメリット

ChatGPTに聞いてみました。

1.ファイルパスの変更が簡単になる
2.コードが読みやすくなる
3.モジュールを別のところでも使える
4.エラーを防ぐ
5.モジュールのグループ化して整理できる

上のようなメリットがあるのでよかったら使ってみてください。もし

import Styled from "../../components/common/Styled";
import Header from "../../components/common/Header";
import Nav from "../../components/common/Nav";
import List from "../../components/users/List";

みたいなのが列挙されていたら読みづらいですよね。😭
僕はこれでエラーで詰まって1時間も解決できずに詰まってしまいました泣。
このやり方をやるとコード読みやすくなりますよ!

公式ドキュメント

書き方は公式ドキュメントで確認してください。

 資料

1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?