Gatsby Plugin Alias Imports

This Gatsby plugin is a wrapper around the webpack feature for aliasing in your import statements.

23rd July 2022

Time to read: 1 min

Logo

So you can do

import '@components/navbar'

Instead of

import '../../components/navbar.js'

This works by simply injecting the options into Webpack using onCreateWebpackConfig.

Install

$ npm i --save gatsby-plugin-alias-imports

or

$ yarn add gatsby-plugin-alias-imports

How to use

Add the plugin to your Gatsby config.

{
  plugins: [
    {
      resolve: `gatsby-plugin-alias-imports`,
      options: {
        alias: {},
        extensions: []
      }
    }
  ]
}

Options

alias

Alias should be an object that takes multiple key/value pairs.

The key should be the alias and the value is the path.

The path that you specify can be relative to the root directory or absolute.

To use an absolute directory, you can do something like

const path = require('path')

// [ ... ]

alias: {
  "@components": path.resolve(__dirname, 'src/components')
}

extensions

The extensions allows you to omit extensions when importing files.

It is an array of desired extensions to auto-find.

E.g. js, css, sass, md

Example

gatsby-config.js

{
  plugins: [
    {
      resolve: `gatsby-plugin-alias-imports`,
      options: {
        alias: {
          "@src": "src",
          "@components": "src/components",
          "@layouts": "src/layouts",
          "@pages": "src/pages",
          "@sass": "src/sass",
          "@templates": "src/templates",
          "@posts": "content/posts",
        },
        extensions: [
          "js",
        ],
      }
    }
  ]
}

index.js

import Layout from '@layouts/main'
import { ComponentA, ComponentB } from '@components/myfile'

Jest Testing

If using Jest then jest.config.js needs to be updated to avoid errors.

// jest.config.js
moduleNameMapper: {
      ".+\\.(css|styl|less|sass|scss)$": `identity-obj-proxy`,
      ".+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": `<rootDir>/tests/__mocks__/file-mock.js`,
      "^@components(.*)$": "<rootDir>/src/components$1",
      "^@data(.*)$": "<rootDir>/src/data$1",
      "^@hooks(.*)$": "<rootDir>/src/hooks$1",
      "^@images(.*)$": "<rootDir>/src/images$1",
      "^@templates(.*)$": "<rootDir>/src/templates$1"
},

Further reading

Check out the resolve section of the Webpack config documentation for more information.