LoginSignup
2
0

More than 1 year has passed since last update.

【Next.js】 コンポーネントを絶対パスとエイリアスで指定する方法

Last updated at Posted at 2021-06-05

はじめに

こんにちわ、dtakkiyです!

Next.jsでプロジェクトが大きくなってきた場合に、コンポーネントを相対パスでリンクさせているとファイルの移動などでミスが出やすくなるかもしれません。またネストが深いとコードの可読性にも問題があります。

そこで今回は、設定ファイルで/srcフォルダを基準に絶対パスで指定する方法を紹介します。
またエイリアスを使った指定方法も紹介します。

Before

import React from 'react'
import Button from '../../../components/home/Button' // 相対パスで指定
import Title from '../../../components/home/Title'   // 相対パスで指定

const About = () => {
  return (
    <div>
      <Title />
      <Button />
    </div>
  )
}

export default About

After

import React from 'react'
import Button from '/src/components/home/Button' // 絶対パスで指定
import Title from '@/components/home/Title'      // エイリアスで指定

const About = () => {
  return (
    <div>
      <Title />
      <Button />
    </div>
  )
}

export default About

ネストも浅くなり、だいぶスッキリしました!

動作検証の環境

  • Next.js: 10.2
  • Javascript

設定方法

まず基準となる親フォルダ/srcを作成します。

$ mkdir src  

次にjsconfig.jsonを作成します。

$ touch jsconfig.json

作成したJSONファイルに以下のキーを設定します。
今回は/srcを基準のフォルダに指定しました。

jsonconfig.json
{
  "compilerOptions": {
    "baseUrl": "/src",
    "paths": {
      "@/components/*": ["src/components/*"] 
    }
  }
}

参考サイト

Absolute Imports and Module path aliases

2
0
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
0