How to import with absolute paths in Gatsby

Clarice Bouwer - Jun 30 '23 - - Dev Community

gatsby-node.js:

const path = require('path')
exports.onCreateWebpackConfig = ({ actions }) => {
  actions.setWebpackConfig({
    resolve: {
      alias: {
        components: path.resolve(__dirname, 'src/components'),
        templates: path.resolve(__dirname, 'src/templates'),
      },
    },
  })
};
Enter fullscreen mode Exit fullscreen mode

./project/src/path/to/some/file/of/yours.js:

import Layout from 'components';
Enter fullscreen mode Exit fullscreen mode

as opposed to:

import Layout from '../../../../components/Layout.js';
Enter fullscreen mode Exit fullscreen mode

See GitHub solution as original source and reference.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .