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

Pausing in a NodeJS HTTP request listener until receiving another response before proceeding

Essentially, this is a web proxy. Within a request listener, I am creating another http request, reading its response, and passing it to the main response. But I have the challenge of needing to wait for the secondary request to complete before continuing. ...

Handling mouse events with Angular 2 (tracking movement based on current position)

One of the features I want to implement for my user is the ability to move or rotate an object in a canvas using the mouse. The process involves calculating the delta (direction and length) between successive mouse events in order to update the position of ...

Verify web connectivity in an Angular2 (non-Ionic) Cordova application

Our team has developed an Angular2 Cordova application (not Ionic) that interacts with multiple backend services. We want the app to display a specific page (Component) if a user is offline. Although we have already created this feature, we are unsure of ...

How can I transfer an instance of a class to dataTransfer.setData?

So I created a new instance of a class: let item = new Item(); Next, I attempted to serialize the item and add it to dataTransfer for drag and drop functionality: ev.dataTransfer.setData("info", JSON.stringify(item)); At some point, I need to retriev ...

Utilizing TypeScript code to access updatedAt timestamps in Mongoose

When querying the database, I receive the document type as a return. const table: TableDocument = await this.tableSchema.create({ ...createTableDto }) console.log(table) The structure of the table object is as follows: { createdBy: '12', cap ...

Struggling to Decode Octet-stream Data in Angular 6 HttpClient: Encountering Parsing Failure with Error Prompt: "Failed to parse HTTP response for..."

Is there a way to make a non-JSON request to the server using Angular 6 HttpClient (@angular/common/http) in order to receive an Octet-stream? Below is the code I have tried: getFile(file: any) { let headers = new HttpHeaders({ 'Content-T ...

Step-by-step guide on uploading an image file using Nextjs

I am attempting to achieve the following: Upload an image file to a Next.js application Process it using cjwbw/real-esrgan:d0ee3d708c9b911f122a4ad90046c5d26a0293b99476d697f6bb7f2e251ce2d4 Retrieve the enhanced version of the image Is there anyone who can ...

Is there a way to monitor user engagement within my app without depending on external analytics platforms?

I'm looking to enhance the user-friendliness of my applications deployed on the Play Store by tracking users' interactions. Specifically, I want to keep track of: Screen Time: Monitoring how much time users spend on each screen. Clicks: Tracking ...

Facing problem with Angular 7 when making a GET request for non-JSON data

Currently, I am retrieving JSON data from a URL using the following method: this.http.get('http://localhost:3200/mydata').subscribe(data => { console.log(data); }); The response is in JSON format, and everything seems to be working fine. ...

Mastering the art of constraining TypeScript function parameters using interface properties

Hey there, I've been exploring ways to restrict a function parameter so that it only accepts "strings" related to interface properties, similar to what I achieved in the validate fields function: Please note: The TypeScript code provided here is simp ...

The exclude option in Nest JS middleware does not prevent the middleware from running on excluded routes

I'm having an issue with excluding certain routes from the middleware. The .exclude option doesn't seem to be working as expected, as the middleware is still being applied to the excluded routes. Here is the code for the Middleware: https://i.st ...

When initiating an Ionic project, you may notice a repeated message in the terminal saying, "[INFO] Waiting for connectivity with npm..."

I'm in the process of setting up a new Ionic project along with all the necessary dependencies. However, whenever I try to execute the command "ionic serve," I keep getting stuck at the continuous display of the message "[INFO] Waiting for connectivit ...

Creating an Angular form from scratch using HTML

I've developed a component named login. Initially, I created an HTML form called login.component.html and then decided to convert it into an Angular form. To achieve this, I inserted <form #loginform="ngForm"> in the login.component.ht ...

The 'style' property is not found within the 'EventTarget' type

Currently, I am utilizing Vue and TypeScript in an attempt to adjust the style of an element. let changeStyle = (event: MouseEvent) => { if (event.target) { event.target.style.opacity = 1; Although the code is functional, TypeScript consist ...

Validate that the input is an array

Looking for a way to determine if a function parameter is an array or not, and then process it accordingly. If the parameter is not an array, convert it into an array before performing the desired function. For example: interface employee { first: st ...

Understanding the timing of records being returned via an Observable in Angular's ngOnInit

In my Angular 2 application, I am using an observable to keep track of an array of records. As the results of this observable are stored in the variable "records", I am utilizing *ngFor="let record of records" to iterate over and display them in my view. ...

Alternatives to using wildcards in TypeScript

In my code, I have defined an interface called ColumnDef which consists of two methods: getValue that returns type C and getComponent which takes an input argument of type C. Everything is functioning properly as intended. interface ColumnDef<R, C> { ...

Creating an Angular table using reactive forms: a step-by-step guide

After reviewing the HTML snippet provided below, it is evident that there is a table with looping through mat cell using *matCellDef="let model". Inside each cell, there are input fields which are reactive forms. Each row or cell needs to have it ...

What techniques can I use to modify an object while it's being iterated through?

I've been attempting to manipulate the object while looping through it, but unfortunately, it's not working. How can I modify it so that the constant patient includes the property lastActivity inside the this.model array? My code looks like this ...

Toggling multiple ions simultaneously does not function independently

I encountered a problem while working on an ionic app. I needed to have individual control over toggle switches, but my current code toggles all switches at once whenever one switch is tapped. Is there a way to fix this and manage each toggle switch separa ...