Currently, I am in the process of developing a component library using React, TypeScript, and Rollup.
Although bundling all components into a single output file index.js
is functioning smoothly, I am facing an issue where individual components do not have their own .js
output files generated.
Nevertheless, my goal is to enable specific imports in my TypeScript projects. For example:
import { ComponentA } from "my-components/lib/ComponentA
;
This approach would ensure that only the required components are included when bundling the project later on.
My main query is: what steps should I take to configure Rollup so that each component has its own output file?
The current file structure appears as follows:
src
│ index.ts
└─components
│ index.ts
├─ComponentA
│ index.ts
│ ComponentA.tsx
└─ComponentB
index.ts
ComponentB.tsx
Here is a snippet of my rollup configuration:
import commonjs from "@rollup/plugin-commonjs";
import resolve from "@rollup/plugin-node-resolve";
import external from "rollup-plugin-peer-deps-external";
import typescript from "rollup-plugin-typescript2";
export default {
input: "src/index.ts",
output: [
{
file: pkg.main,
format: "cjs",
exports: "named",
sourcemap: true
},
{
file: pkg.module,
format: "es",
exports: "named",
sourcemap: true
}
],
plugins: [
external(),
resolve({
browser: true
}),
typescript({
rollupCommonJSResolveHack: true,
exclude: "**/__tests__/**",
clean: true
}),
commonjs({
include: ["node_modules/**"],
exclude: ["**/*.stories.js"],
namedExports: {
"node_modules/react/react.js": [
"Children",
"Component",
"PropTypes",
"createElement"
],
"node_modules/react-dom/index.js": ["render"]
}
})
]
};
Upon execution, the outputs are found in the 'lib' directory as listed below:
lib
│ index.d.ts
│ index.es.js
│ index.es.js.map
│ index.js
│ index.js.map
└─components
│ index.d.ts
├─ComponentA
│ index.d.ts
│ ComponentA.d.ts
└─ComponentB
index.d.ts
ComponentB.d.ts
My ultimate objective is to have separate .js files for each component in the 'lib' folder such as ComponentA.js
and ComponentB.js
.