create custom components library with styled components and publish to npm

In most cases its better to customize a pre-built such as material design than build your own from scratch, but I wanted to use this as a learning opportunity and build out my own component library

Technology used

  • react
  • typescript
  • styled-components
  • storybook
  • jest and react-testing-library
  • rollup - module bundler

setup
yarn init 
yarn add --dev typescript 
yarn add --dev react-dom react @types/react-dom @types/react
yarn add --dev styled-components
yarn add --dev @types/styled-components

ran `npx tsc --init` to create default tsconfig.json and then customized


add rollup, so installing it and dependencies:
yarn -D add rollup
yarn -D add @rollup/plugin-node-resolve @rollup/plugin-commonjs @rollup/plugin-typescript rollup-plugin-peer-deps-external rollup-plugin-terser rollup-plugin-dts
yarn -D add tslib

then create the rollup.config.js file and edited it


I created /src/components/index.js and then created /src/components/Button

to build run `yarn run build`

At this stage code is generated in /dist folder for commonjs and es6 modules folders.

add storybook
`npx sb init`

change /.storybook/main.js to reference 1 folder down in stories
add stories for my new Button component


add jest and react-testing-library
`yarn -D add @testing-library/react @testing-library/jest-dom @testing-library/user-event  jest @types/jest jest-environment-jsdom`

init jest config file: `npx jest --init`

now if we run `yarn run test` we see jest run 

to support typescript and run jest tests faster I installed swc core and its jest runner
`yarn add -D @swc/core`
`yarn add -D @swc/jest`
and updated package.json transform per @swc/jest 

next add tests
then run tests

react-testing-library has updated guidance for userEvent for setup and await


npm publish
`npm login`
`npm publish`


and here is the final product: my custom component library deployed on npm ðŸ’¥

(stoked!)


references









Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more