Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript & Gatsby: Development bundle cannot resolve paths but VS Code can

I have a bunch of imports like import Navi from 'components/Navi'

These have a red error line under the components/Navi part until I add this to my tsconfig.json

"baseUrl": "./",
"paths": {
  "components/*": ["src/components/*"],
  "layouts/*": ["src/layouts/*"],
  "pages/*": ["src/pages/*"],
  "templates/*": ["src/templates/*"],
  "scss/*": ["src/scss/*"],
  "types": ["src/types"]
}

At which point the error goes away. When I try to build my develop bundle through running gatsby develop everything looks fine until this appears ⠹ Building development bundle

Which is followed shortly by lots of statements like Can't resolve 'components/Navi' in '~/src/components'

And these errors only go away when I specify a relative path like import Navi from '../Navi'


As a side note, I also can't do import {MyType} from 'types' with a structure of

src
    -> types
        -> index.ts

It gives an error with a red line under the word 'types' which states Cannot find module 'types'.ts(2307) And I must change the import to import {Issue} from 'types/index'


I already tried running gatsby clean and deleting node_modules

like image 458
Sam Avatar asked Feb 11 '26 01:02

Sam


1 Answers

Shubham's solution still works as of June 2021 - if you want it automatically resolve all dirs under src, you can use a little two-liner I wrote for this:

const fs = require("fs");
const path = require("path");

const srcDirs = fs.readdirSync(path.resolve(__dirname, "src"));

const rootDirsConfig = {};

srcDirs.forEach((srcDir) => {
    rootDirsConfig[srcDir] = path.resolve(__dirname, "src", srcDir);
});

module.exports = {
    plugins: [
          {
            resolve: "gatsby-plugin-root-import",
            options: rootDirsConfig,
          },
    ]
}
like image 62
Antoni Papiewski Avatar answered Feb 13 '26 18:02

Antoni Papiewski