So I'm trying to build a generic component in a separate repo from a project. The components repo is an npm package. I will include the code so you can tell me what I'm doing wrong?
My component is in: src/components/table/Table.tsx
;
really simple code:
const Table = () => {
const [test, setTest] = useState(1);
return <div>Test</div>
}
export default Table;
Then I have the index.ts
file with this:
import Table from './components/table/Table.tsx';
export { Table };
Then I have the package.json
with the build command for development:
"main": "dist/bundle.js",
"scripts": {
"dev": "webpack --watch --mode development"
}
Then the webpack config file:
const path = require("path");
module.exports = {
entry: "./src/index.ts",
module: {
rules: [
{
test: /\.tsx?$/,
use: "babel-loader",
exclude: /node_modules/
},
]
},
resolve: {
extensions: [".tsx", ".ts", ".js"],
alias: {
"@": path.resolve(__dirname, "src")
}
},
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist"),
libraryTarget: "umd",
library: "my-library"
}
};
And then in the other project I have the package JSON where I import my package (locally for now, for developemnt):
"dependencies": {
"@myuser/my-library": "file:../my-library",
}
And then I import the component:
import { Table } from '@myuser/my-library';
And then use it:
const MyComponent = () => {
return (
<div>
<Table />
</div>
)
}
And it throws:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
But if I remove the useState
in the Table
component then it works all perfectly.