gatsby-plugin-babel-module-resolver
Description
Custom module resolver plugin for Babel for Gatsby.
Why?
It’s fewer characters? Sure, but the real benefit comes during a refactor. When your moving files around you don’t have to manage your ../‘s
Install
npm i gatsby-plugin-babel-module-resolver && npm i -D @babel/core babel-plugin-module-resolver
or
yarn add gatsby-plugin-babel-module-resolver && yarn add -D @babel/core babel-plugin-module-resolver
Usage
By default you can import from the root of the src
directory directly.
gatsby-config.js
// gatsby-config.js
module.exports = ['gatsby-plugin-babel-module-resolver'];
With the above config you can import ./src/components/layout.js
into ./src/pages/index.js
like so:
import Layout from 'components/layout';
Adding Alias Options
gatsby-config.js
// gatsby-config.js
module.exports = {
plugins: [
{
resolve: 'gatsby-plugin-babel-module-resolver',
options: {
root: ['./src/'],
alias: {
data: './data/test',
'@utils': './utils',
},
},
},
],
};
ESlint Config
npm i -D eslint-plugin-import eslint-import-resolver-babel-module
or
yarn add -D eslint-plugin-import eslint-import-resolver-babel-module
If eslint is still drawing redlines, but your modules & alias are working and match the paths in your gatsby-config, reload your editor.
.eslintrc
"settings": {
"import/no-unresolved": 2,
"import/resolver": {
"node": {
"moduleDirectory": ["node_modules", "src"],
},
"babel-module": {
"root": ["./src"],
"alias": {
"data": "./data/test",
"components": "./src/components",
"@utils": "./utils",
},
}
}
}
JS Config
This plugin can mess with your import suggestions. To fix this add a jsconfig.json
to the root of your Gatsby project. (Link below for more info on jsconfig files.)
jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": ["./*"],
"data": ["data"],
"data/*": ["data/*"],
"components": ["src/components"],
"components/*": ["src/components/*"],
"@utils": ["utils"],
"@utils/*": ["utils/*"]
}
}
}
https://code.visualstudio.com/docs/languages/jsconfig
How to contribute
If you have unanswered questions, would like help with enhancing or debugging the plugin, reach out @ jameygleason.com.
License
MIT © jameygleason