alexeagleson / template-react-component-library Goto Github PK
View Code? Open in Web Editor NEWA component library for React
A component library for React
Hi @alexeagleson thanks for great article!
I facing an issue that reported as
I have followed the Adding Rollup section, but somehow when i publish the lib into registry and install the lib on my own project, it raise an error like picture i provided aboves
Heres my rollup config
import commonjs from "@rollup/plugin-commonjs";
import resolve from "@rollup/plugin-node-resolve";
import terser from "@rollup/plugin-terser";
import typescript from "@rollup/plugin-typescript";
import dts from "rollup-plugin-dts";
import peerDepsExternal from "rollup-plugin-peer-deps-external";
import packageJson from "./package.json" assert { type: "json" };
export default [
{
input: "src/index.ts",
output: [
{
file: packageJson.main,
format: "cjs",
sourcemap: true,
},
{
file: packageJson.module,
format: "esm",
sourcemap: true,
},
],
plugins: [
peerDepsExternal(),
resolve(),
commonjs(),
typescript({ tsconfig: "./tsconfig.json" }),
terser(),
],
external: [...Object.keys(packageJson.peerDependencies || {})],
},
{
input: "dist/esm/types/index.d.ts",
output: [{ file: "dist/types.d.ts", format: "esm" }],
plugins: [dts()],
},
];
Thanks in advance!
When i add Material UI component and try to use component in another react project, it throw Error Regarding hooks.
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
can you please help me to understand why i am getting this ?
I am able to build the project fine locally, but when I attempt to build in a github action, I am getting an error. Any advice or input would be appreciated :)
src/index.ts → dist/cjs/index.js, dist/esm/index.js...
[!] Error: Could not resolve './Button.css' from src/components/Button/Button.tsx
Error: Could not resolve './Button.css' from src/components/Button/Button.tsx
package.json
{
"name": "REDACTED",
"version": "0.1.4",
"description": "REDACTED",
"scripts": {
"build": "rollup -c",
"test": "jest",
"storybook": "start-storybook -p 6006",
"build-storybook": "build-storybook"
},
"author": "REDACTED",
"license": "ISC",
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"files": [
"dist"
],
"publishConfig": {
"registry": "https://npm.pkg.github.com/@REDACTED"
},
"types": "dist/index.d.ts",
"devDependencies": {
"@babel/core": "^7.19.1",
"@babel/preset-env": "^7.19.1",
"@babel/preset-react": "^7.18.6",
"@babel/preset-typescript": "^7.18.6",
"@mdx-js/react": "^2.1.3",
"@rollup/plugin-commonjs": "^22.0.2",
"@rollup/plugin-node-resolve": "^14.1.0",
"@rollup/plugin-typescript": "^8.5.0",
"@storybook/addon-actions": "^6.5.12",
"@storybook/addon-essentials": "^6.5.12",
"@storybook/addon-interactions": "^6.5.12",
"@storybook/addon-links": "^6.5.12",
"@storybook/builder-webpack5": "^6.5.12",
"@storybook/manager-webpack5": "^6.5.12",
"@storybook/react": "^6.5.12",
"@storybook/testing-library": "^0.0.13",
"@testing-library/react": "^13.4.0",
"@types/jest": "^29.0.2",
"@types/react": "^18.0.19",
"babel-jest": "^29.0.3",
"babel-loader": "^8.2.5",
"css-loader": "^6.7.1",
"html-webpack-plugin": "^5.5.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^29.0.3",
"jest-environment-jsdom": "^29.0.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"rollup": "^2.79.0",
"rollup-plugin-dts": "^4.2.2",
"rollup-plugin-postcss": "^4.0.2",
"sass": "^1.54.9",
"sass-loader": "^13.0.2",
"style-loader": "^3.3.1",
"tslib": "^2.4.0",
"typescript": "^4.8.3"
}
}
Rollup config:
import resolve from "@rollup/plugin-node-resolve"; // build modules
import commonjs from "@rollup/plugin-commonjs"; // convert commonjs modules to es6 modules
import typescript from "@rollup/plugin-typescript"; // process typescript
import dts from "rollup-plugin-dts"; // process type definitions
import postcss from "rollup-plugin-postcss"; // process styles
const packageJson = require("./package.json");
export default [
{
input: "src/index.ts",
output: [
{
file: packageJson.main,
format: "cjs",
sourcemap: true,
},
{
file: packageJson.module,
format: "esm",
sourcemap: true,
},
],
plugins: [
resolve(),
commonjs(),
typescript({ tsconfig: "./tsconfig.json" }),
postcss(),
],
},
{
input: "dist/esm/index.d.ts",
output: [{ file: "dist/index.d.ts", format: "esm" }],
plugins: [dts()],
external: [/\.(css|less|scss)$/],
},
];
tsconfig:
{
"compilerOptions": {
"target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
"strict": true /* Enable all strict type-checking options. */,
"skipLibCheck": true /* Skip type checking all .d.ts files. */,
"jsx": "react",
"module": "ESNext",
"declaration": true,
"declarationDir": "types",
"sourceMap": true,
"outDir": "dist",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"emitDeclarationOnly": true
}
}
Action:
# This workflow will run tests using node and then publish a package to GitHub Packages when the main branch is pushed to
# For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages
name: REDACTED
on:
push:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 16
- run: npm ci
- run: npm test
publish-gpr:
needs: build
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 16
registry-url: https://npm.pkg.github.com/
- run: npm ci
- run: npm run build
- run: npm publish
env:
NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}
I created a similar template which is more up to date: https://github.com/morewings/react-library-template.
I update dependencies every month.
After having this problem with my own package after falling your tutorial, I checked via a fork of your repo if it was an issue with the original too. Apparently it is... while the component seems to be functioning as expected, here's what it does at startup:
$ yarn start
yarn run v1.22.17
warning ..\..\package.json: No license field
$ react-scripts start
(node:31496) [DEP_WEBPACK_DEV_SERVER_ON_AFTER_SETUP_MIDDLEWARE] DeprecationWarning: 'onAfterSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.
(Use `node --trace-deprecation ...` to show where the warning was created)
(node:31496) [DEP_WEBPACK_DEV_SERVER_ON_BEFORE_SETUP_MIDDLEWARE] DeprecationWarning: 'onBeforeSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.
Starting the development server...
Compiled with warnings.
Failed to parse source map from 'C:\Users\kkrasnowsky\work\test-lib-app\node_modules\@languagelinetranslation\template-react-component-library\src\components\Button\Button.tsx' file: Error: ENOENT: no such file or directory, open 'C:\Users\kkrasnowsky\work\test-lib-app\node_modules\@languagelinetranslation\template-react-component-library\src\components\Button\Button.tsx'
Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
assets by path static/ 1.58 MiB
asset static/js/bundle.js 1.57 MiB [emitted] (name: main) 1 related asset
asset static/js/node_modules_web-vitals_dist_web-vitals_js.chunk.js 6.93 KiB [emitted] 1 related asset
asset static/media/logo.6ce24c58023cc2f8fd88fe9d219db6c6.svg 2.57 KiB [emitted] (auxiliary name: main)
asset index.html 1.67 KiB [emitted]
asset asset-manifest.json 546 bytes [emitted]
cached modules 1.46 MiB (javascript) 31.3 KiB (runtime) [cached] 123 modules
WARNING in ./node_modules/@languagelinetranslation/template-react-component-library/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\Users\kkrasnowsky\work\test-lib-app\node_modules\@languagelinetranslation\template-react-component-library\src\components\Button\Button.tsx' file: Error: ENOENT: no such file or directory, open 'C:\Users\kkrasnowsky\work\test-lib-app\node_modules\@languagelinetranslation\template-react-component-library\src\components\Button\Button.tsx'
@ ./src/App.tsx 5:0-83 45:37-43
@ ./src/index.tsx 7:0-24 11:33-36
1 warning has detailed information that is not shown.
Use 'stats.errorDetails: true' resp. '--stats-error-details' to show it.
webpack 5.67.0 compiled with 1 warning in 8463 ms
Files successfully emitted, waiting for typecheck results...
Issues checking in progress...
No issues found.
any ideas on how to fix this?
After following the guide for adding Typescript here I was still getting the following error when trying to import from a CSS module
(!) Plugin typescript: @rollup/plugin-typescript TS2307: Cannot find module './Component.module.scss' or its corresponding type declarations.
src/components/Component/Component.tsx: (3:20)
import styles from "./Component.module.scss"
I fixed this by adding a typings.d.ts
file to the src
directory with the following contents:
declare module "*.module.css";
declare module "*.module.scss";
I based this solution on this SO thread.
Hopefully this can be added to this project and help others. Thanks!
awesome article and repo! Just missing one library
"react-dom": "^17.0.2",
Once I installed it, then I could run storybook
Just cloned the project, ran npm i && npm run rollup
(!) Plugin typescript: @rollup/plugin-typescript TS4023: Exported variable 'LoggedOut' has or is using name 'PageProps' from external module "/Users/maximelechevallier/Documents/MyProjects/template-react-component-library/src/stories/Page" but cannot be named.
src/stories/Page.stories.tsx: (20:14)
20 export const LoggedOut = Template.bind({});
Env used:
"rollup": "^3.22.0",
"typescript": "5.0.4",
"react": "^18.2.0" // as peer dependency
Whenever I am using a hook inside any component of the created library it throws the error -
ERROR
Cannot read properties of null (reading 'useState')
TypeError: Cannot read properties of null (reading 'useState')
at useState (http://localhost:3000/main.969d555df88fb2dbc6ad.hot-update.js:2183:25)
at Header (http://localhost:3000/main.969d555df88fb2dbc6ad.hot-update.js:185:70)
at renderWithHooks (http://localhost:3000/static/js/bundle.js:21238:22)
at mountIndeterminateComponent (http://localhost:3000/static/js/bundle.js:24524:17)
at beginWork (http://localhost:3000/static/js/bundle.js:25820:20)
at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:10830:18)
at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:10874:20)
at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:10931:35)
at beginWork$1 (http://localhost:3000/static/js/bundle.js:30805:11)
at performUnitOfWork (http://localhost:3000/static/js/bundle.js:30052:16)
My Code:
import React, { useState } from 'react';
import styles from './header.module.scss';
const Header = () => {
// const [{ date, time }]= [{ date: '14 May', time: '11:30:03 PM' }];
const [{ date, time }]= useState<{ date: string, time: string }>({ date: '14 May', time: '11:30:03 PM' });
return (
<header className={styles.header}>
...
</header>
);
}
Integrated env:
import React from 'react';
import { MyComponent } from 'my-lib';
function App() {
return (
<div className="App">
<MyComponent />
</div>
);
}
export default App;
maybe this issue is not with the above repo, please someone help me with the same? Becuase the same error I received when creating the setup using Webpack 5.
More details:
function resolveDispatcher() {
var dispatcher = ReactCurrentDispatcher.current;
{
if (dispatcher === null) {
error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
}
} // Will result in a null access error if accessed outside render phase. We
// intentionally don't throw our own error because this is in a hot path.
// Also helps ensure this is inlined.
return dispatcher;
}
function useState(initialState) {
var dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
dispatcher
in the above function is returned as null
. though same thing is supposed to be managed by react.
Issue is fixed when adding "rootDir": "src"
in tsconfig.json
file.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.