I want to switch an existing Gatsby project to TypeScript, I followed the official Gatsby TypeScript example to do so, but VSCode always complains about the imports from gatsby
.
Cannot find module 'gatsby' or its corresponding type declarations.ts(2307)
I'm using the latest version of Gatsby and tried reinstalling node_modules.
I've also noticed, after reinstalling Gatsby, VSCode is trying for quite a while to load the declaration files which ultimately isn't successful.
You can checkout this repo which I'm trying to convert to TypeScript, some pages are already .tsx
files. You can clone the project and open it with VSCode to see if the imports work for you.
VSCode should be able to use the type declarations inside gatsby.
VSCode doesn't find the gatsby module or type declarations
System:
OS: macOS 10.15.5
CPU: (8) x64 Intel(R) Core(TM) i7-4750HQ CPU @ 2.00GHz
Shell: 5.7.1 - /bin/zsh
Binaries:
Node: 12.4.0 - ~/.nvm/versions/node/v12.4.0/bin/node
Yarn: 1.22.4 - ~/.nvm/versions/node/v12.4.0/bin/yarn
npm: 6.10.0 - ~/.nvm/versions/node/v12.4.0/bin/npm
Languages:
Python: 2.7.17 - /usr/local/bin/python
Browsers:
Chrome: 83.0.4103.116
Safari: 13.1.1
npmPackages:
gatsby: ^2.23.11 => 2.23.11
gatsby-image: ^2.2.29 => 2.2.37
gatsby-plugin-google-analytics: ^2.0.13 => 2.1.23
gatsby-plugin-layout: ^1.0.11 => 1.1.13
gatsby-plugin-manifest: ^2.2.23 => 2.2.34
gatsby-plugin-offline: ^3.0.16 => 3.0.30
gatsby-plugin-react-helmet: ^3.1.13 => 3.1.18
gatsby-plugin-root-import: ^2.0.5 => 2.0.5
gatsby-plugin-sharp: ^2.2.32 => 2.3.10
gatsby-source-filesystem: ^2.1.33 => 2.1.33
gatsby-source-shopify: ^3.0.24 => 3.0.37
gatsby-transformer-sharp: ^2.3.0 => 2.3.9
Information from VSCode
Version: 1.46.1
Commit: cd9ea6488829f560dc949a8b2fb789f3cdc05f5d
Date: 2020-06-17T21:17:14.222Z (1 wk ago)
Electron: 7.3.1
Chrome: 78.0.3904.130
Node.js: 12.8.1
V8: 7.8.279.23-electron.0
OS: Darwin x64 19.5.0
This issue disappeared for me when setting:
"target": "es5",
"module": "commonjs",
@insuusvenerati Thanks, fixed it for me as well! Still wondering though why the Gatsby TypeScript example uses esnext
as target and module.
"moduleResolution" is classic when "module" is esnext. VSCode cannot find "node_modules/gatsby/index.d.ts" because of that.
Details of moduleResolution.
There are also solutions below.
"moduleResolution": "node"
"moduleResolution" is classic when "module" is esnext. VSCode cannot find "node_modules/gatsby/index.d.ts" because of that.
Details of moduleResolution.There are also solutions below.
"moduleResolution": "node"
It worked for me, thanks legend
Most helpful comment
This issue disappeared for me when setting: