Create React Package in Typescript in 5 Minutes
Setup a react npm package to share components or other modules in 5 minutes, without getting hands dirty.
A lot of tutorials online use webpack or even create-react-app to setup a react package. There are drawbacks for those methods:
- The
babel-*
dependencies bundle doesn’t come for free and usually hard to understand webpack.config.js
and.babelrc
could be hard to get them right
This tutorial gives you a silly simple way to create a react package without those drawbacks but the benefit from TypeScript: build time type checking (You can opt-out this benefit by writting just JavaScript). Which means your package is born with TypeScript support.
Jump to Source Code.
Setup
Create folders and files
1 | mkdir -p react-greeting/src # create folder |
Initialize yarn and add dependencies
1 | yarn init -y |
Minimal setup only requires react
and typescript
, @types/react
is here to make your life even easier.
Add tsconfig.json
with
1 | { |
Optional but recommended
Add README.md
and LICENSE
1 | touch README.md LICENSE # update content as you like |
Add .gitignore
with
1 | node_modules/ |
Initialize git
1 | git init |
Develop
Create src/index.ts
with
1 | import Greeting from './Greeting' |
Create src/Greeting.tsx
with
1 | import React from 'react' |
This creates a Greeting
component which could pass in an optional prop name
, then render a h1
element with a greeting message. (Obviously!)
Build
Update package.json
with scripts
and types
so it looks like this
1 | { |
scripts
add a convenient script to build the package, types
indicates where to find type definition file.
Build package
1 | yarn build |
This builds out several *.js
and *.d.ts
, those are the only files which are actually needed to be packaged and published.
Publish
Add .npmignore
with
1 | # Ignore unnecessary files |
Publish to npm
1 | yarn publish --access public |
DONE~!
Test
Testing is not included in this post for simplicity, but there are two major tests you could do with your new component.
Unit Test
Checkout Jest and Enzyme to write unit test inside your package.
Here is an example unstated-typescript
Integrated Test
Test the package inside a react app using yarn link technique.