Create a React lib and publish to NPM
Create the folder for the project and init yarn in it
create the folder
mkdir mylib
go into the folder
cd mylib
initialize npm
yarn init
initialize git
git init
Install React and Typescript
yarn add -d react react-dom @types/react typescript
react and react-dom should also be added to the peerDependencies in the package.json
...
"peerDependencies": {
"react": "^16.8.0",
"react-dom": "^16.8.0"
},
...
now configure Typescript by creating a tsconfig.json file in the root folder for the project and add
{
"compilerOptions": {
"target": "es5",
"outDir": "lib",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"declaration": true,
"declarationDir": "lib",
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
],
"exclude": [
"node_modules",
"lib"
]
}
Install Storybook
npx sb init
point the stories to go in the src folder by changing the .storybook/main.js file
...
"stories": [
"../src/**/*.stories.tsx"
],
...
Install Rollup for the build of the lib
yarn add --dev rollup rollup-plugin-typescript2 @rollup/plugin-commonjs @rollup/plugin-node-resolve rollup-plugin-peer-deps-external rollup-plugin-postcss postcss
add the target for publishing in package.json
{
...
"main": "lib/index.js",
"module": "lib/index.esm.js",
"types": "lib/index.d.ts",
...
}
create a rollup.config.json file with
import peerDepsExternal from "rollup-plugin-peer-deps-external";
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "rollup-plugin-typescript2";
import postcss from "rollup-plugin-postcss";
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: [
peerDepsExternal(),
resolve(),
commonjs(),
typescript({ useTsconfigDeclarationDir: true }),
postcss({
extensions: ['.css']
})
]
};
and add the build script to package.json
{
...
"scripts": {
...
"build": "rollup -c"
},
...
}
publish to npm
npm publish