21
Steps to create a React Typescript library
This post will help you to publish your own react library to npm, so you can reuse your own component and functions.
This post is intended for people who just want to follow the steps without understand the details.
Before start, You will need to have NPM, Typescript and other common dev dependencies installed
First, create
tsconfig.json
file at your project root:{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"declaration": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react",
"outDir": "lib/esm",
},
"include": [
"src"
],
"exclude": ["node_modules", "lib"]
}
then run
npm init
, and modify package.json
flie:...
"main": "./lib/cjs/index.js",
"module": "./lib/esm/index.js",
"types": "./lib/esm/index.d.ts",
"files": [
"src"
],
"scripts": {
"build": "npm run build:esm && npm run build:cjs",
"build:esm": "tsc",
"build:cjs": "tsc --module commonjs --outDir lib/cjs",
"publish": "npm publish"
},
...
"peerDependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"@types/node": "16.11.10",
"@types/react": "^17.0.37"
},
"dependencies": {
"@types/react-dom": "^17.0.11"
}
...
}
Add
.gitignore
file if you are using git:# dependencies
/node_modules
Create
src
folder and src/index.tsx
file:import React from "react";
export function CheckLib(){
return <div>Lib Ok</div>
}
Then run
npm run build
to create the build folder.Run
npm publish
to publish your package.Finally, you can use
npm install <your-package-name>
to install your library in other project.You may need to run npm login
to login your npm account if you never logged in before.
If you want to have a playground of your library or just want to use it.
Run
In your other project root run
After this, you should be able to find your library inside the node_modules folder.
npm link
at your library root.In your other project root run
npm link "You-Library-Name-Here"
.After this, you should be able to find your library inside the node_modules folder.
I tested this method with a project created by
If you find your project does not run your library, you may need to explore some more complex methods.
I'm using Windows for this method, if you're using Mac or other OS you may want to change build script to work with your CLI environment.
create-next-app
. I assume this will work CRA as well.If you find your project does not run your library, you may need to explore some more complex methods.
I'm using Windows for this method, if you're using Mac or other OS you may want to change build script to work with your CLI environment.
Thanks
21