React Component Library With TypeScript
Here's a guide to create a React component library with TypeScript given by ChatGPT.
To create a TypeScript React component library project, you can follow these steps:
mkdir my-library
cd my-library
npm init -y
, this will create a package.json
file in the root directory.module
in package.json
: {
"type": "module"
}
npm install --save-dev typescript react react-dom @types/react @types/react-dom
npm install --save-dev rollup rollup-plugin-typescript2 rollup-plugin-peer-deps-external rollup-plugin-commonjs rollup-plugin-node-resolve
Here, we are installing TypeScript, React, and their respective type definitions. We are also installing Rollup and its plugins for bundling and transpiling our code.
tsconfig.json
file in the root directory: {
"compilerOptions": {
"outDir": "./dist/",
"module": "esnext",
"target": "es5",
"lib": ["es6", "dom"],
"sourceMap": true,
"declaration": true,
"declarationMap": true,
"jsx": "react",
"esModuleInterop": true
},
"include": ["src/**/*"]
}
This sets up the TypeScript compiler options. We are targeting ES5 with support for ES6 and DOM types. We are also declaring our component interfaces for external use and generating source maps.
rollup.config.js
file in the root directory: import typescript from 'rollup-plugin-typescript2';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
export default {
input: 'src/index.tsx',
output: [
{
file: 'dist/bundle.js',
format: 'cjs',
sourcemap: true
},
{
file: 'dist/bundle.esm.js',
format: 'esm',
sourcemap: true
}
],
plugins: [
peerDepsExternal(),
resolve(),
commonjs(),
typescript({
rollupCommonJSResolveHack: true,
clean: true
})
]
};
This sets up Rollup to bundle our code. We are setting the input file to src/index.tsx
and outputting two bundles: one in CommonJS format (dist/bundle.js
) and one in ES module format (dist/bundle.esm.js
).
src
directory in the root directory.index.tsx
file in src
directory: export { default as ComponentName } from './ComponentName';
This exports our component from src/ComponentName.tsx
.
src/ComponentName.tsx
: import React from 'react';
interface Props {
name: string;
}
const ComponentName: React.FC<Props> = ({ name }) => {
return <div>Hello, {name}!</div>;
};
export default ComponentName;
This creates a simple component that takes a name
prop and displays it in a div.
npx rollup -c
test
directory and a test.tsx
file: import React from 'react';
import { ComponentName } from '../dist/bundle';
export default function Test() {
return <ComponentName name="World" />;
}
This imports our component from the dist/bundle
file and uses it in a simple test.
npx parcel test.html
(assuming you have Parcel installed)That's it! You now have a basic TypeScript React component library. You can continue adding components to the src
directory and building them with Rollup.