In the Gatsby Project, we can create reusable components/functions in different folders. We can then import these components/functions in the page components to use in the website to add functionality and UI.
As a developer, we need to organize these components/functions into different folder categories. If the components reside deep into the folder hierarchy, we may end up writing the code as below:
import Bio from '../../../../../../components/bio'
The above kind of import is not what we want. But... we want to import components as below.
import Bio from '@components/bio'
In order to make the above import work in Gatsbyjs, we need to include Aliasing for the components directory.
In order to include aliases in Gatsby, you can add the below line of code in the gatsby-node.js
.
const path = require(`path`)
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
resolve: {
alias: {
"@components": path.resolve(__dirname, "src/components"),
"@lib": path.resolve(__dirname, "src/lib"),
"@styles": path.resolve(__dirname, "src/styles"),
"@utils": path.resolve(__dirname, "src/utils"),
},
},
})
}
In the above code, we added the following folder for aliases as below.
components
,lib
,styles
,utils
After adding the above code, you need to restart Gatsby serve. Stop the Gatsby localhost serve from the terminal by pressing CTRL+C
and re-run Gatsby's localhost server by executing the below command from the terminal.
npm run develop
Now, in the Gatsby project, we can update the import line of code as below:
Great!