Building React components for Gatsby using NPM link and Hooks – Cant resolve ‘react’ solution
I have been working on components for Gatsby JS, and including React Hooks. The idea is they will be packaged up separately and pushed to NPM. To make the build easier I house the component in a separate directory and npm link to a Gatsby test site.
Everything was going well until I introduced the hooks.
Hook Error: Hooks can only be called inside the body of a function component
After many hours, it turns out that React should be a peer dependency in a package. As I had React set as a standard dependency in the plugin, it was loading twice! I sorted this, then another got error:
Module not found: Error: Can’t resolve ‘react’
Ok. So I have removed the extra version of React,. Now it cannot see any. Ok….
Turns out that if you request React in a Gatsby plugin, but don’t include it as a dependencies, Gatsby cannot see it. This is due to the way the transpiler works in Gatsby. To fix this, you need to tell Webpack to link up any React requirements (This is only needed when developing).
After many hours, the solutions was the following:
//gatsby-node.js
const path = require("path");
exports.onCreateWebpackConfig = ({
stage,
rules,
loaders,
plugins,
actions,
}) => {
actions.setWebpackConfig({
resolve: {
alias: {
react: path.join(process.cwd(), "node_modules/react"),
},
},
});
};
This finds any reference to React and ensures it has been linked up properly. Such a simple fix to such a messy problem.
Thanks to these links:
https://www.mrozilla.cz/blog/gatsby-eslint-vscode-import-alias/
https://github.com/babel/babel-loader/issues/149