0
0

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)にて絶対パスでimportする方法

Posted at

Next.js(React)では、デフォルトだとコンポーネントなどを相対パスでimportするようになっています。
本記事では、Next.jsにて絶対パスでimportする方法を解説しています。

jsconfig.json(tsconfig.json)で設定する

Next.jsのjsconfig.jsonに下記の設定を追加します。(※TypeScriptの場合はtsconfig.jsonです。)

jsconfig.json
{
  "compilerOptions": {
    "baseUrl": "."
  },
}

baseUrlにオプションを設定することで、絶対パスでimportすることができます。

index.tsx
// import Layout from '../components/layout/Layout'
import Layout from 'components/layout/Layout' // 絶対パスで指定

const Home = () => {
  return (
    <>
      <Layout />
    </>
  )
}

export default Home

Visual Studio Code(VSCode)にて自動で絶対パスをimportする

VSCodeではコンポーネントなどを記述する際に自動でimportしてくれる機能があります。
自動importを絶対パスにするには、VSCodeの設定を変更します。

設定を開いて下記の画像のようにJavaScript › Preferences: Import Module Specifiernon-relativeに設定します。

next.js絶対パス.png

上記の設定をすることでbaseUrlに基づいてimportをしてくれるようになります。

ちなみにVSCodeではjsonファイルで設定を管理することもできます。
.vscodeディレクトリのsettings.jsonファイルで管理します。

next.js vscode.png

settings.json
{
  "javascript.preferences.importModuleSpecifier": "non-relative"
}

最後に

本記事ではNext.jsにて絶対パスでimportする方法を解説してきました。
プロジェクトが大きくなり、ディレクトリの階層が深くなる場合などは絶対パスの方が便利かなと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?