Developing a unique component library with react, typescript, and webpack
Encountering an issue when utilizing components outside of react
Received an error message: invalid hook call. Hooks can only be called inside the body of a function component.
Also experiencing occasional errors like:
TypeError: Cannot read properties of null (reading 'useContext') useContext /node_modules/react/cjs/react.development.js:1618
Attempted to resolve by adjusting versions of react and other dependencies
Package.json
{
"name": "library",
"version": "1.0.0",
"main": "dist/index.js",
"license": "MIT",
"devDependencies": {
"@types/react": "^17.0.43",
"bootstrap": "^4.6.0",
"html-webpack-plugin": "^5.5.0",
"ts-loader": "^9.4.2",
"typescript": "^4.9.4",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1",
"webpack-node-externals": "^3.0.0"
},
"scripts": {
"build": "webpack",
"tsc": "tsc",
"start": "react-scripts start"
},
"dependencies": {
"@emotion/react": "^11.10.5",
"@emotion/styled": "^11.10.5",
"@material-ui/core": "^4.11.2",
"@material-ui/lab": "4.0.0-alpha.61",
"@material-ui/styles": "^4.11.5",
"@mui/material": "^5.10.7",
"@types/react-dom": "^18.0.10",
"material-avatar": "^0.3.5",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-script": "^2.0.5"
},
"peerDependencies": {
"react": "*",
"react-dom": "*"
},
"files": [
"./dist"
]
}
.tsx file
import React from "react";
import Button from '@mui/material/Button';
interface ButtonProps {
items: itemsArrayInterface[];
title: String
}
interface itemsArrayInterface {
id: Number,
addedBy: String,
page: String,
likes: String,
unLikes: String,
adminApproved: String,
comments: String,
time: string,
rating: Number
}
export default function(props: ButtonProps){
return (
<>
<Button>hello</Button>
</>
)
}
Webpack configuration
const path = require("path");
const HTMLWebpackPlugin = require("html-webpack-plugin");
const nodeExternals = require("webpack-node-externals");
module.exports = {
entry: "./src/index.tsx",
mode: "production",
target: "node",
output: {
path: path.resolve(__dirname, "dist"),
filename: "index.js",
libraryTarget: "umd",
library: "library",
},
plugins: [
new HTMLWebpackPlugin({
template: path.join(__dirname, "src", "index.html"),
}),
],
module: {
rules: [
{
test: /\.tsx?/,
use: [
{
loader: "ts-loader",
options: {
compilerOptions: {
noEmit: false,
},
},
},
],
},
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
],
},
externals: [nodeExternals()],
resolve: {
extensions: [".tsx", ".ts", ".js", ".d.ts"],
},
};
Typescript (ts) configuration
{
"compilerOptions": {
/* TypeScript Configuration */
"target": "es6",
"lib": [
"es6",
"dom"
],
"jsx": "react",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noImplicitThis": true,
"skipLibCheck": true
},
"include": [
"src"
]
}