2
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 3 years have passed since last update.

GatsbyJSファイルを絶対パスでimportできるよう gatsby-plugin-root-import を使ってみた

Last updated at Posted at 2020-10-30

GatsbyJSを触っていてbaseUrlみたいに絶対パスを指定したい時のまとめ

gatsby-plugin-root-importを使う

公式サイト:https://www.gatsbyjs.com/plugins/gatsby-plugin-root-import/

結論から言うと gatsby-plugin-root-import をインストールすればOKです。ただし、gatsby-config.jsへ書き込みが必要です。

npm install --save-dev gatsby-plugin-root-import
もしくは
yarn add --dev gatsby-plugin-root-import

をインストールしてきましょう。

親ディレクトリの位置に gatsby-config.js ファイルを作る

公式と内容が被りますがここでは src のみを絶対パスとしてエイリアスにする設定を書きました。

gatsby-config.js
const path = require('path')

module.exports = {
  /* Your site config here */
  plugins: [
    {
      resolve: 'gatsby-plugin-root-import',
      options: {
        src: path.join(__dirname, 'src')
      }
    }
  ],
}

resolve: に今回インストールしたライブラリ名を指定し、optionsにどこの絶対パスにするかを指定しています。
src: という名前でこの名前のパスが path.join(__dirname, 'src') であると設定しています。

読み込んでみた

再度 develop し直して読み込んでみました。下のように記述を直しても読み込むことができました。

gatsby-browser.js
import '../styles/style.css'

import "src/styles/style.css"

baseUrlと違って "src" と入力することに違和感があるかもしれませんがエイリアスで簡単に絶対Pathを追加できるので便利です。

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