Outputting a JS file per component using Rollup and Typescript

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Notifying users when a document is nearing its expiration date in the most effective manner

In my calendar app, I set appointments to automatically delete after 5 minutes. Now, I want to retrieve all appointments that are about to expire within 1 minute and send a notification to the front-end indicating their impending expiration. Although I at ...

Wait for a minimum of X milliseconds using RxJS

I'm attempting to achieve a specific functionality using RxJS: Trigger an event Make an API call Upon receiving the API response, do one of the following: Wait for at least X milliseconds after triggering the event If X milliseconds have already p ...

What could be causing Typescript to inaccurately infer the type of an array element?

My issue revolves around the object named RollingStockSelectorParams, which includes arrays. I am attempting to have TypeScript automatically determine the type of elements within the specified array additionalRsParams[title]. The main question: why does ...

Using a variety of objects in TypeScript arrays

How to effectively implement a superior class in TypeScript for an array containing diverse objects that inherit from the same class, without triggering errors? This is my attempt: interface IVehicle{ modelName: string } interface ICar extends IVehi ...

React component's state is not being correctly refreshed on key events

Currently facing an issue that's puzzling me. While creating a Wordle replica, I've noticed that the state updates correctly on some occasions but not on others. I'm struggling to pinpoint the exact reason behind this discrepancy. Included ...

Sharing interfaces and classes between frontend (Angular) and backend development in TypeScript

In my current project, I have a monorepo consisting of a Frontend (Angular) and a Backend (built with NestJS, which is based on NodeJS). I am looking to implement custom interfaces and classes for both the frontend and backend. For example, creating DTOs s ...

Filtering data on objects in Angular can be achieved by utilizing the built-in

Retrieving data from the backend using this function: private fetchData(): void { this.dataService.fetchData().pipe( tap((response: any) => { this.persons = response.results; this.familyMembersTrue = this.persons.filter(x =&g ...

Utilize TypeScript to access scope within a directive

Is there a way to access the controller's scope properties using my custom TypeScript directive? For example, in this snippet below, I am trying to retrieve and log scope.message: /// <reference path="typings/angularjs/angular.d.ts" ...

Issue with dynamically typed object properties in Typescript codebases

Check out this TypeScript code snippet: export type Mutation = (state: State, data: unknown) => void export type Mutations = { [key: string]: Mutation } private buildMutations(): Mutations { return { ['3']: (state, data) => ...

Typescript error: The value "X" cannot be assigned to this type, as the properties of "Y" are not compatible

Disclaimer: I am relatively new to Angular2 and typescript, so please bear with me for any errors. The Challenge: My current task involves subtracting a start date/time from an end date/time, using the result in a formula for my calculation displayed as " ...

Prevent click events on disabled tabs in PrimeNG tabMenu

I am encountering an issue with PrimeNG's p-tabMenu when it comes to disabled menu items. For example, suppose I have a tabMenu with 4 sub tabs labeled AAA, BBB, CCC, and DDD. This is how the menuItems are set up in the TypeScript component: //.... ...

Eliminate duplicate dropdown options in Angular 2 using a filter function

Is there a way to filter reporting results in an Angular 2 dropdown list? I am currently attempting to do so within the *ngFor template but haven't had any success. I will also try using a custom pipe. The data is coming from a JSON array. Specificall ...

To continue receiving rxjs updates, kindly subscribe if the specified condition is met

Is there a way to check a condition before subscribing within the operator chain? Here's what I have: // parentElem:boolean = false; // the parent elem show/hide; let parentElem = false; // inside the ngAfterViewInit(); this.myForm.get('grandPa ...

Find the appropriate return type for a TypeScript function based on its argument

Is it feasible in TypeScript to infer the return type of a function based on its arguments? This feature would be beneficial when extracting specific properties from, for example, a database query. Here is an illustration (https://repl.it/repls/Irresponsi ...

What is the best way to incorporate Firebase into an Angular 2 TypeScript application without relying on AngularFire?

What is the best way to integrate Firebase into an Angular 2 TypeScript application without relying on AngularFire? I have a simple Angular 2 application and I am looking to incorporate Firebase into it. ...

Increasing a value within HTML using TypeScript in Angular

I'm working with Angular and I have a TypeScript variable initialized to 0. However, when trying to increment it using *ngFor in my .ts file, the increment is not happening (even though the loop is running correctly). my-page.html <div *ngFor=&quo ...

How can I activate TypeScript interface IntelliSense for React projects in VSCode?

Did you know that there are TypeScript interfaces designed for DOM, ES5, and other JavaScript modules? I am curious if it is feasible to have intellisense similar to the one provided by TypeScript Playground for various interfaces in a React project. ...

Encountering ReferenceError when attempting to declare a variable in TypeScript from an external file because it is not defined

Below is the typescript file in question: module someModule { declare var servicePort: string; export class someClass{ constructor(){ servicePort = servicePort || ""; //ERROR= 'ReferenceError: servicePort is not defined' } I also attempted t ...

Setting up a Variable with an Object Attribute in Angular

I am attempting to create a variable that will set a specific property of an object retrieved through the get method. While using console.log in the subscribe function, I am able to retrieve the entire array value. However, as a beginner, I am struggling ...

TS2365: The '!== 'operator is not compatible with the types ""("" and "")""

function myFunction(identifier: string) { identifier = "("; }; let identifier: string = ")"; if (identifier !== '(') throw "Expected '(' in function"; myFunction(identifier); if (identifier !== ')') throw "Expected &a ...