I have written a React hook in Typescript and would like to publish it to npm, but I can't seem to get the build configuration correct. I'm not using any other build tool besides tsc. I have read the recommendations in the Typescript docs, React docs, and a few blog posts.
I don't get any errors when I build and publish, but when I try to import the module in another project I get an error importing React. Yet everything I've ready suggests that react should be a peerDependency when publishing custom hooks.
Cannot find module 'react' from '../useMyHook/build/index.js'
- tsc:
v4.1.3 - react:
v16.14.0
Repo: https://github.com/raineorshine/use-swipe-to-dismiss
tsconfig.json:
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"declaration": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"target": "es5",
"outDir": "./build"
},
"include": ["src"],
"exclude": ["node_modules", "**/__tests__/*"]
}
package.json (abbreviated):
{
"name": "useMyHook",
"version": "0.1.0",
"files": [
"build/**/*"
],
"main": "build",
"scripts": {
"build": "tsc",
"prepare": "npm run build"
},
"peerDependencies": {
"react": ">=16.0.0",
"typescript": ">=4.1.0"
},
"devDependencies": {
"@types/node": "^14.14.21",
"@types/react": "^17.0.0"
}
}
index.ts (abbreviated):
import { useState } from 'react'
const useMyHook = () => {
const [x, setX] = useState<number>(0)
return {
onClick: () => {
console.log(x)
}
}
}
export default useMyHook