This article will take you through the manner of creating and publishing your personal custom react aspect library and web hosting it on github.
At the cease of this academic you will have the ability to the following in all your destiny react tasks:
npm installation @my-github-account/my-cool-component-library
import mycustomcomponent from ‘@my-github-account/my-cool-thing-library’;
const myapp = () =>
go back (
<div>
<mycustomcomponent />
</div>
)
stipulations and setup
this undertaking assumes you’re acquainted with and have hooked up:
code editor / ide (this academic uses vs code however any ide will work)
npm (npm is established whilst you set up node. Js on your device)
installing programs (presume you realize a way to upload programs to a javascript undertaking with npm set up)
bash terminal (or another terminal you’re comfortable with for running commands)
git (we are able to be developing a git repository on our system and publishing it to github, even though all instructions might be provided on how to comply with along)
react (how to create simple additives the use of jsx)
typescript (the way to create an object interface with simple homes)
first we will initialize our assignment. Npm init
you can take the defaults for all the values, we will edit them later inside the academic. Next we can upload add the tools necessary to create our components. Npm install react typescript @sorts/react –store-dev
Developing
Now we will create our first aspect. Because we are creating a library, we are going to create index files for every tier, and export our additives from each one to make it as smooth as feasible for the human beings the use of our library to import them.
Inside the root of your mission, create the subsequent record shape:
.
├── src
│ ├── components package. Json
└── package deal-lock. Json
Make sure to double test your shape. You should have 3 index. Ts files, and a button. Tsx document internal of a button listing. If you have a favored manner of structuring react additives within a project you are of direction welcome to do it but you want, but that is the structure we can observe for this educational.
Begin through creating button. Tsx:
src/additives/button/button. Tsx
import react from “react”;
export interface buttonprops
label: string;
const button = (props: buttonprops) =>
go back <button>props. Label</button>;
;
export default button;
To preserve matters simple we are able to simply export a button that takes a unmarried prop referred to as label. We will upload greater complexity and patterns to our additives as soon as we’ve confirmed that our fundamental template is setup efficiently.
After our button, we replace the index file internal our button directory:
src/additives/button/index. Ts
export default from “./button”;
then we export that button from the additives listing:
src/additives/index. Ts
export default as button from “./button”;
and eventually, we are able to export all of our components from the bottom src listing:
src/index. Ts
export * from ‘./components’;
adding typescript
up until now, we haven’t yet initialized typescript in our venture. Even though you technically don’t want a configuration report to use typescript, for the complexity of constructing a library we are truly going to want one.
You may initialize a default configuration with the aid of walking the subsequent command:
npx tsc –init
So one can create a tsconfig. Json record for us within the root of our mission that contains all the default configuration options for typescript. In case you would really like to learn more about the various options in a tsconfig. Json file, cutting-edge versions of ts will mechanically create descriptive feedback for each price. In addition you could find complete documentation at the configuration right here. You may note depending on your ide that at once after initializing you start to get errors to your venture. There are two motives for that: the first is that typescript isn’t configuration to understand react through default, and the second is that we have not described our method for handling modules but: so it may now not recognize the way to manage all of our exports.
To restore this we are going to upload the following values to tsconfig. Json:
“compileroptions”:
// default
“goal”: “es5”,
“esmoduleinterop”: proper,
“forceconsistentcasinginfilenames”: real,
“strict”: real,
“skiplibcheck”: actual,
// introduced
“jsx”: “react”,
“module”: “esnext”,
“statement”: proper,
“declarationdir”: “types”,
“sourcemap”: real,
“outdir”: “dist”,
“moduleresolution”: “node”,
“allowsyntheticdefaultimports”: proper,
“emitdeclarationonly”: genuine,
We have separated these values into a pair unique sections based totally on the default tsconfig. Json created the use of the maximum latest model of typescript as of this writing (4. 4). The values commented default ought to already be set for you by default (you may want to double test and ensure but).
The values marked added are new values that we want for our undertaking. We will in brief outline why we want them:
“jsx”: “react” — remodel jsx into react code
“module”: “esnext” — generate modern js modules for our library
“statement”: genuine — output a . D. Ts report for our library types
“declarationdir”: “types” — where to region the . D. Ts documents
“sourcemap”: genuine — mapping js code returned to its ts report origins for debugging
“outdir”: “dist” — directory in which the venture might be generated
“moduleresolution”: “node” — follow node. Js regulations for locating modules
“allowsyntheticdefaultimports”: genuine — assumes default exports if none are created manually
“emitdeclarationonly”: actual — don’t generate js (rollup will try this) handiest export kind declarations
One you upload those values to your ts configuration record you have to see the mistakes in button. Tsx and other files straight away disappear. Adding rollup
Subsequent we will upload rollup to our assignment. If you’ve never used rollup before, it’s very similar to webpack in that it’s miles a device for bundling character javascript modules right into a single source that a browser is higher able to understand. Though each gear can accomplish the equal purpose depending on configuration, generally webpack is used for bundling programs at the same time as rollup is mainly suitable for bundling libraries (like ours). It’s why we’ve chosen rollup. Additionally just like webpack, rollup uses a plugin environment. By means of design rollup does now not realize a way to do the whole lot, it is based on plugins mounted in my view to feature the capability which you want.
We’re going to rely on 4 plugins for the initial configuration of our library (more could be added later):
@rollup/plugin-node-clear up – uses the node resolution set of rules for modules
@rollup/plugin-typescript – teaches rollup the way to process typescript documents
@rollup/plugin-commonjs – converts commonjs modules to es6 modules
rollup-plugin-dts – rollup your . D. Ts documents
so with that said, allow’s move ahead and set up rollup and our plugins:
npm set up rollup @rollup/plugin-node-remedy @rollup/plugin-typescript @rollup/plugin-commonjs rollup-plugin-dts –shop-dev
To configure how rollup goes to package our library we want to create a configuration record within the root of our project:
rollup. Config. Js
import clear up from “@rollup/plugin-node-remedy”;
import commonjs from “@rollup/plugin-commonjs”;
import typescript from “@rollup/plugin-typescript”;
import dts from “rollup-plugin-dts”;
const packagejson = require(“./package deal. Json”);
export default [
enter: “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” ),
],
,
enter: “dist/esm/types/index. D. Ts”,
output: [ file: “dist/index. D. Ts”, format: “esm” ],
plugins: [dts()],
,
];
In this report we import our 4 plugins that we established. We also import our package. Json report as a commonjs module int oa variable called packagejson. We use this variable to refer to the primary and module values that we can outline in the next segment. The entrypoint for our library (input) is the index. Ts file within the src listing which exports all of our additives. We can be distributing both es6 and commonjs modules so the purchasers of our library can choose which type work excellent for them. We additionally invoke 3 of our four plugins on the first of configuration items at the exported array. This primary configuration defines how the actual javascript code of our library is generated. The second configuration item defines how our libraries types are dispensed and makes use of the dts plugin to accomplish that.
The final step earlier than we will run our first rollup is to define the values of “most important” and “module” in our package deal. Json document:
package deal. Json
“name”: “template-react-thing-library”,
“model”: “0. Zero. 1”,
“description”: “a easy template for a custom react factor library”,
“scripts”:
“rollup”: “rollup -c”
,
“author”: “alex eagleson”,
“license”: “isc”,
“devdependencies”:
“@rollup/plugin-commonjs”: “^21. Zero. 1”,
“@rollup/plugin-node-clear up”: “^13. Zero. 6”,
“@rollup/plugin-typescript”: “^8. Three. Zero”,
“@types/react”: “^17. 0. 34”,
“react”: “^17. Zero. 2”,
“rollup”: “^2. 60. Zero”,
“rollup-plugin-dts”: “^four. Zero. 1”,
“typescript”: “^4. Four. Four”
,
“important”: “dist/cjs/index. Js”,
“module”: “dist/esm/index. Js”,
“documents”: [
“dist”
],
“sorts”: “dist/index. D. Ts”
here is the pattern of the package. Json report we’re the usage of for this academic. Glaringly your creator call can be one of a kind, and the precise model of every of your libraries might be unique as nicely. The most critical modifications are as follows:
“fundamental” — we have described the output course for commonjs modules
“module” — we’ve described the output path for es6 modules
“documents” — we’ve defined the output listing for our complete library
“types” — we’ve got defined the place for our library’s sorts
“scripts” — we’ve described a brand new script known as rollup. This could run the rollup bundle with the -c flag this means that “use the rollup configuration report”. In case you’re now not acquainted with script in a package deal. Json document, those are without a doubt shorthand commands you could run by using name with npm run scriptname. So that you can run this one can be npm run rollup. Constructing your library
with these configurations in region you are now equipped to run rollup for the first time and ensure your fundamental configuration is correct.
Your task structure must seem like this before you run:
.
├── src
│ ├── additives │ └── index. Ts
│ └── index. Ts
├── package. Json
├── package deal-lock. Json
├── tsconfig. Json
└── rollup. Config. Js
the contents of every file must be as defined above. As soon as you’ve got showed this, run the subsequent command:
npm run rollup
if the whole lot has been configured efficaciously rollup will run with out errors and you will see a dist directory created within the root of your venture with a structure that looks as if:
dist directory
(if you obtained an error make certain to read it closely to try and become aware of the difficulty. Double check that every of your documents follows exactly the shape of the examples. Relying on the amount of time handed since the publishing of this educational, new principal versions of libraries may want to potentially be published with breaking changes. All variations of libraries numbers are seen above in the package. Json example in the event you need to specify a particular model)
publishing your library
Now that we’ve created our thing library, we need a way to allow ourselves (or others) to download and installation it. We will be publishing our library via npm through web hosting on github. First earlier than anything else we need to create a repository for our library. Create a new repository on github. I have titled mine template-react-thing-library. Then observe the steps to initialize your project as a git project, and push in your new repository. Log into github and create a brand new repository referred to as whatever you want. For this example i’ve titled it template-react-aspect-library and it’ll be available for anyone to clone and use publicly. You can choose to make your library non-public if you like, techniques defined on this academic will work for non-public applications as properly (if you are creating a library for your organisation for example). As soon as the repository is created we want to initialize git inside our undertaking domestically.
Run the following command:
git init
next create a . Gitignore report inside the root of the directory (make specific word of the main length, that indicates that is a hidden record):
. Gitignore
dist
node_modules
in our . Gitignore report we’re adding the dist and node_modules directories. The motive being that each of these are vehicle-generated directories that we create using instructions, so there is no want to consist of them in our repository. Now observe the instructions on github shown in your new repository for committing your code. This repository that you have created is the one you may clone & edit whilst you want to make adjustments and updates for your issue library. This isn’t always the package deal itself that your (as a user) would install and use. To configure within our mission in which our bundle needs to be published to, next we need to replace package deal.
Json with that facts:
package. Json
“name”: “@your_github_username/your_repository_name”,
“publishconfig”:
“registry”: “https://npm. Pkg. Github. Com/your_github_username”
,
… You will be updating the sphere “name” fee and adding a brand new field known as “publishconfig”. Word the values above in caps are meant to get replaced together with your own values. For example my “name” subject cost would be @alexeagleson/template-react-issue-library. Word the “packageconfig” additionally has your github account call in it as properly, but that value does no longer lead with the @ image. Now that we’ve got configured out undertaking, we need to configure our nearby install of npm itself to be legal to post to your github account. To try this we use a . Npmrc record. This report isn’t a part of our undertaking. That is a international document in a principal place. For mac/linux customers it goes in your home listing ~/. Npmrc. For windows users it is going in your house directory as nicely, though the syntax can be one-of-a-kind. Some thing along the traces of c:customersyour_windows_username
For greater statistics approximately this configuration record study this. As soon as you have created the document, edit it to encompass the subsequent records:
~/. Npmrc
registry=https://registry. Npmjs. Org/
@your_github_username:registry=https://npm. Pkg. Github. Com/
//npm. Pkg. Github. Com/:_authtoken=your_auth_token
There are two values in caps to update in the example above. The primary is your_github_username. Make certain to include the main @ symbol. The second one is your_auth_token which we haven’t created but. Lower back to github! Go to your github profile: settings -> developer settings -> personal access tokens. Or just click on this link
Click on generate new token. Deliver it a name that suits the challenge you are building. Give it an expiry date (github recommends you do not create tokens with an countless lifespan for protection reasons, but it is as much as you). The maximum essential issue is to click on the write:packages get admission to value. This may give your token permission to read & write packages to your github account, that’s wht we need. Generate new token
Once you are carried out you may click to create the token. Github will best display you the token once. While you near/refresh the page it will be long gone, so ensure to duplicate it to a secure area (perhaps a password supervisor in case you use one). The main place you need to location this token is inside the ~/. Npmrc document that you created changing the your_auth_token price from the example above. Earlier than you continue, do one greater sanity check to be sure you did not create the . Npmrc record inside the root listing of your actual library task. This is technically an choice, however the purpose you need to be careful is that you can accidentally commit it to your github repository with the rest of your library code and reveal your token to the public. If your . Npmrc report is in your private home directory the danger of this is minimized. At this point, when you ~/. Npmrc document has both your github username and get right of entry to token delivered, move returned in your venture listing and run the subsequent command:
npm submit
(if you get induced for login credentials, the username is your github username and your password is the get admission to token you generated)
congratulations! You’ve got now published version zero. 0. 1 of your react element library! You can view it to your github account through going in your primary account dashboard and clicking “applications” along the pinnacle to the proper of “repositories”::
github applications
the usage of your library
Now that your library is stay, you’ll need to apply it! Word that the commands for using your library are barely different if you published to a non-public repository. Every person (aside from your own device) who tries to import it’s miles going to get a 404 now not found errors if they’re now not legal. Those customers also want to add a ~/. Npmrc file with the equal information. To be greater relaxed but you could provide those customers with an get entry to token that has most effective study privileges, not write.
(from this factor onward we can presume you have completed that step, or are operating with a public repository.)
Due to the fact that we’ve got created a aspect library using react and typescript, we’re presuming that the customers of our library could be the use of those equipment as properly. Technically all of our type files (. D. Ts) are supplemental: that means they’re honestly omitted if running with trendy javascript, so it is now not vital to apply typescript to use our library. The types are simply there if preferred. For our instance we can use it but so that we can confirm that they’re working nicely. We are able to initialize a react app the use of one of the maximum popular and easy techniques: create react app. Run the following command in a brand new directory:
(take into account we are simulating different customers downloading and installing our library, so this task ought to be completely break free the library itself)
npx create-react-app my-app –template typescript
open the new my-app directory that is created and run:
npm run begin
Verify which you are able to open and cargo the default application display screen on localhost:3000 (or whatever port it opens on). Now comes the check for our library. From the root listing of your new my-app mission, run the subsequent command:
npm install @your_github_username/your_repository_name
so for my venture as an instance its: npm set up @alexeagleson/template-react-component-library
presuming your tokens and configuration are set up properly, the entirety will installation efficaciously (if there are any problems, revisit the example for the ~/. Npmrc config.)
Now open the my-app undertaking in your ide of desire (vs code for instance) and navigate to the src/app. Tsx file. When you go to add a <button /> issue, in case your editor supports import automobile entire (ctrl/cmd + . For vs code) then you will see it automatically recognize thanks to typescript that our library exports that button. Car import
we could add it! The handiest example to replace src/app. Tsx is:
src/app. Tsx
import react from “react”;
import button from “@alexeagleson/template-react-factor-library”;
feature app()
return <button label=”hello world!”/>;
export default app;
and when we run npm run start again, there tucked up inside the corner is our hello world! Button. Hiya global button
and that’s it! Congratulations! You now have all the gear you need to create and distribute a react factor library the usage of typescript! At this point you end the tutorial and continue for your personal in case you want. If you choose to retain, we can examine a way to enlarge our element library to include a number of extremely useful functions which include:
css: for exporting components with style
storybook: for testing our components inside the library itself as we layout them
react testing library & jest: for testing our additives
adding css
Before we do any additional configuration, we’ll start by developing a css report with a view to follow a few patterns to our button. Inner of the button directory where our issue lives, we’ll create a file called: button. Css:
src/components/button/button. Css
button
font-size: 60px;
This can flip our regular good day international! Button into a in reality big button. Next we are able to suggest that these styles are meant to be carried out on our button component. We’re going to be using unique syntax that isn’t native to javascript, but thanks to rollup and an appropriate plugins, we’re able to use it. Update our button.
Tsx report with the following:
src/additives/button/button. Tsx
import react from “react”;
import “./button. Css”;
export interface buttonprops
label: string;
const button = (props: buttonprops) =>
return <button>props. Label</button>;
;
export default button;
observe the import ‘./button. Css’ that has been brought. Now we want to tell rollup a way to system that syntax.
To do this we use a plugin called rollup-plugin-postcss. Run the following command:
npm installation rollup-plugin-postcss –store-dev
subsequent we want to update our rollup config:
rollup. Config. Js
import resolve from “@rollup/plugin-node-resolve”;
import commonjs from “@rollup/plugin-commonjs”;
import typescript from “@rollup/plugin-typescript”;
import dts from “rollup-plugin-dts”;
// new
import postcss from “rollup-plugin-postcss”;
const packagejson = require(“./bundle. Json”);
export default [
enter: “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” ),
// new
postcss(),
],
,
enter: “dist/esm/types/index. D. Ts”,
output: [ file: “dist/index. D. Ts”, format: “esm” ],
plugins: [dts()],
// new
external: [/. Css$/],
,
];
Be aware the 3 new lines indicated with the new remarks. Inside the dts config we need to specify that . Css modules are outside and need to not be processed as a part of our type definitions (otherwise we are able to get an error). Subsequently we want to replace the version quantity in our package. Json report. Do not forget we’re publishing a bundle so while we make changes, we need to make sure we don’t impact customers of preceding versions of our library.
Whenever we publish we must increment the model number:
package deal. Json
“version”: “0. Zero. 2”,
… Now run those instructions:
npm run rollup
npm post
On the library consuming side (my-app react app from our instructional) we also need to update to get the contemporary model of the package deal. The very best manner is to increment the version range in the bundle. Json record of my-app. It must display ^zero. 0. 1. Increment that to ^0. Zero. 2 and then you could update with the npm install command:
npm install
npm run start
and you will be dealt with to a large button issue from our library that now supports bundling css! Huge button
optimizing
there are multiple easy optimizations we will make with this setup. The primary is to feature a plugin referred to as terser a good way to minify our package deal and reduce the overall file size. The alternative is to replace a number of our dependencies to peerdependencies. With rollup’s peer dependencies plugin we can inform the initiatives that are using our libraries which dependencies are required (like react) but might not honestly package a duplicate of react with the library itself. If the purchaser already has react in their mission it will use that, in any other case it will get hooked up once they run npm deploy. First we can set up those plugins:
npm set up rollup-plugin-peer-deps-outside rollup-plugin-terser –shop-dev
then we are able to update our rollup config:
rollup. Config. Js
import solve from “@rollup/plugin-node-clear up”;
import commonjs from “@rollup/plugin-commonjs”;
import typescript from “@rollup/plugin-typescript”;
import postcss from “rollup-plugin-postcss”;
import dts from “rollup-plugin-dts”;
//new
import terser from “rollup-plugin-terser”;
import peerdepsexternal from ‘rollup-plugin-peer-deps-external’;
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: [
// new
peerdepsexternal(),
resolve(),
commonjs(),
typescript( tsconfig: “./tsconfig. Json” ),
postcss(),
// new
terser(),
],
,
input: “dist/esm/kinds/index. D. Ts”,
output: [ file: “dist/index. D. Ts”, format: “esm” ],
plugins: [dts()],
outside: [/. Css$/],
,
];
then we circulate react from devdependencies to peerdependencies in our bundle. Json report:
package deal. Json
“devdependencies”:
“@rollup/plugin-commonjs”: “^21. 0. 1”,
“@rollup/plugin-node-clear up”: “^thirteen. 0. 6”,
“@rollup/plugin-typescript”: “^8. Three. 0”,
“@types/react”: “^17. Zero. 34”,
“rollup”: “^2. 60. Zero”,
“rollup-plugin-dts”: “^4. Zero. 1”,
“rollup-plugin-peer-deps-outside”: “^2. 2. Four”,
“rollup-plugin-postcss”: “^4. Zero. 1”,
“rollup-plugin-terser”: “^7. 0. 2”,
“typescript”: “^4. Four. Four”
,
“peerdependencies”:
“react”: “^17. 0. 2”
,
… Including checks
To add exams for our additives we are going to set up react trying out library, and to run the ones tests we can install jest. Npm install @checking out-library/react jest @types/jest –save-dev
internal of our button listing, create a new report called button. Test. Tsx
src/additives/button/button. Test. Tsx
import react from “react”;
import render from “@checking out-library/react”;
import button from “./button”;
describe(“button”, () =>
test(“renders the button factor”, () =>
render(<button label=”hello world!” />);
);
);
What this could do is render our button on a non-browser dom implementation and ensure that it mounts well. This is a totally simple check, but it serves as an amazing instance of the syntax you may use to get started out. To head deeper intensive read further within the react testing library documentation. Earlier than we are able to run the exams we want to configure jest, and create a take a look at runner script in our bundle. Json. We will begin with the configuration, create a jest. Config. Js file inside the root of the mission:
jest. Config. Js
module. Exports =
testenvironment: “jsdom”,
;
this tells jest to use jsdom as our dom implementation. Subsequent update your package deal. Json document:
package deal. Json
“scripts”:
“rollup”: “rollup -c”,
“take a look at”: “jest”
,
… Now we will run our exams with:
npm run test
Unluckily we are going to get an blunders! The mistake is while our jsx code is encountered. If you recall we used typescript to address jsx with our rollup config, and a typescript plugin for rollup to teach it the way to try this. We don’t have any such setup in region for jest unfortunately. We are going to want to install babel to deal with our jsx differences. We will additionally want to install a jest plugin called babel-jest that tells jest to apply babel! Allow’s set up them now, at the side of babel plugins to address our typescript and react code. The total series of they all looks like:
npm set up @babel/core @babel/preset-env @babel/preset-react @babel/preset-typescript babel-jest –shop-dev
Now we create our babel configuration document in the root of our undertaking, which tells babel to apply a majority of these plugins we’ve just established:
babel. Config. Js
module. Exports =
presets: [
“@babel/preset-env”,
“@babel/preset-react”,
“@babel/preset-typescript”,
],
;
Now we have to be able to run our checks with npm run check… However… There may be one extra hassle! You may get an mistakes announcing the import of the . Css file isn’t understood. That makes experience because, again, we configured a postcss plugin for rollup to deal with that, but we did no such issue for jest. The final step will be to install a bundle referred to as identification-obj-proxy. What this does is let you configure jest to treat any sort of imports as simply established items. So we’ll do that with css files so we don’t get an errors. Npm install identification-obj-proxy –keep-dev
We need to update our jest config tp encompass the modulenamemapper assets.
We’ve got additionally added much less and scss in there for right degree in case you need to enlarge your project later to apply those:
jest. Config. Js
module. Exports =
testenvironment: “jsdom”,
modulenamemapper: lessscss)$”: “identification-obj-proxy”,
,
;
now in the end if you’ve followed up step up up to now, you can run:
npm run test
and you will be treated to a a hit check! Jest test
adding storybook
Storybook is a a tool for visualizing ui components outside of your website / application. It’s awesome for prototyping and checking out distinct visual states of components to make certain they paintings the manner they’re designed to, without the extra overhead of having other unrelated components on the display screen. It additionally offers you an smooth manner to peer and use your additives while running on them in your library task, without having to construct an needless testing web page simply to display them. Initializing storybook is very smooth. To set it up and configure it mechanically we just run the following command:
npx sb init
not like some of the other equipment we have added up to now, storybook a good deal extra of a “batteries included” sort of bundle that handles most of the initial setup for you. It will even add the scripts to run it into your bundle. Json file robotically. You’ll additionally be aware that it creates a tales listing on your src directory. This listing is full of pre-built templates with a purpose to use as an example of a way to create your own stories. I endorse you don’t delete these till you grow to be acquainted with storybook and the way to write your personal stories, having them close by will be very available. Now permit’s create a easy story for our button.
Create a new report in the button listing known as button. Stories. Tsx:
src/components/button/button. Memories. Tsx
import react from “react”;
import componentstory, componentmeta from “@storybook/react”;
import button from “./button”;
// greater on default export: https://storybook. Js. Org/medical doctors/react/writing-stories/creation#default-export
export default
name: “reactcomponentlibrary/button”,
element: button,
as componentmeta<typeof button>;
// greater on element templates: https://storybook. Js. Org/medical doctors/react/writing-tales/creation#using-args
const template: componentstory<typeof button> = (args) => <button … Args />;
export const helloworld = template. Bind();
// greater on args: https://storybook. Js. Org/docs/react/writing-stories/args
helloworld. Args =
label: “hi there international!”,
;
export const clickme = template. Bind();
clickme. Args =
label: “click me!”,
;
This might be a bit overwhelming at first, but whilst you undergo it piece through piece you have to see it’s pretty trustworthy. The default export defines wherein the button will seem within the storybook. I have selected reactcomponentlibrary as a easy call to institution our custom additives collectively separately from the examples. The template determines which element is surely being rendered, and which default args/props to apply to it. The template. Bind gadgets are instances or instance states of the component. So in a real undertaking you may have something like “largebutton” and “smallbutton”. Seeing that our button is continually big i have simply used an example of trying out the button with distinct labels. If you have a look at your bundle. Json file you will see that storybook has already delivered a storybook and storybook-build script. The first will host the storybook software domestically for short and smooth testing. The second will construct a static html/js bundle that can without problems be hosted on a far flung server, so all participants of your group can try your components. For now permit’s just run:
npm run storybook
edit: it’s feasible you may come across errors because of lacking dependencies. If this takes place there are a few answers. The primary is to install the ones dependencies manually. As an example react-dom. This is not ideal as your undertaking itself need to not rely on those libraries, so it must no longer be essential to consist of them as they’re protected with storybook’s peer dependencies, as instance right here. In case you without a doubt run a sparkling npm deploy command it will install all the peerdependencies of the libraries you’re the use of. Earlier than strolling this you can want to delete your bundle-lock. Json and node_modules listing. They may be regenerated robotically after your clean deploy. It is able to be complicated to troubleshoot issues related to both overlapping and lacking dependencies among libraries. Stay affected person and ensure to read your mistakes messages!)
if all is going well you’ll be greeted with a friendly interface that helps you to navigate through the instance additives in addition to your personal custom button in real time. Click on between them to check out the different states which you have created. Storybook example
there may be lots extra to study storybook, make certain to examine thru the documentation. Wrapping up
you have to now have a terrific know-how about how to create your very own react factor library. Doing so cannot handiest teach you a lot about how the javascript bundle control surroundings works, however it could be a terrific way to make code which you use across more than one projects effortlessly to be had with a simple command.