Tips for preventing repetition of code in multiple entry points in Rollup

My goal is to use rollup to process a group of input files and generate multiple output files in the dist directory that all have some common code shared between them.

Below is my current rollup configuration:

import path from 'path';
import pathsTransformer from 'ts-transform-paths';
import alias from '@rollup/plugin-alias';
import commonjs from '@rollup/plugin-commonjs';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import typescript from 'rollup-plugin-typescript2';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';

const plugins = [
  peerDepsExternal(),
  alias({
    entries: [
      { find: '@', replacement: path.join(__dirname, '/src') },
      { find: '$root', replacement: __dirname },
    ],
  }),
  nodeResolve(),
  typescript({
    transformers: [() => pathsTransformer()],
  }),
  commonjs({
    extensions: ['.js', '.ts'],
  }),
];

export default [
  {
    input: './src/a.ts',
    output: {
      file: 'dist/a.js',
      format: 'esm',
      sourcemap: true,
    },
    plugins,
  },
  {
    input: './src/b.ts',
    output: {
      file: 'dist/b.js',
      format: 'esm',
      sourcemap: true,
    },
    plugins,
  },
];

The issue I am facing with this setup is that when both a.ts and b.ts rely on the same code, that common code gets bundled into each output file, needlessly increasing the bundle size.

Since the output.format is esm where imports are available in the output, I would expect rollup to separate the shared code into a distinct chunk and then have both files import that common code (which appears to be the default behavior of rollup).

I suspect the problem lies within the nodeResolve or commonjs calls, but I still want my dependencies to be bundled, just without duplicating them.

How can I optimize my output? Here's a link to a repository for demonstration (with the 'dist' folder included).

Answer №1

When you return an array of objects to rollup, you are indicating that you want to generate independent bundles. However, if your goal is simply to create multiple files (which was the case for me), you can achieve this by specifying the input as an object.

import path from 'path';
import pathsTransformer from 'ts-transform-paths';
import alias from '@rollup/plugin-alias';
import commonjs from '@rollup/plugin-commonjs';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import typescript from 'rollup-plugin-typescript2';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';

const plugins = [
  peerDepsExternal(),
  alias({
    entries: [
      { find: '@', replacement: path.join(__dirname, '/src') },
      { find: '$root', replacement: __dirname },
    ],
  }),
  nodeResolve(),
  typescript({
    transformers: [() => pathsTransformer()],
  }),
  commonjs({
    extensions: ['.js', '.ts'],
  }),
];

export default   {
  input: {
    a: './src/a.ts',
    b: './src/b.ts',
  },
  output: {
    dir: 'dist',
    format: 'esm',
    sourcemap: true,
  },
  plugins,
};

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

How can I style the empty text in an ExtJS grid using CSS?

Is there a specific CSS class for a grid's emptyText? After inspecting the element with Firebug, all I found was: <div id="gridview-1021" class="x-component x-grid-view x-fit-item x-component-default x-unselectable" role="presentation" tabindex=" ...

When attempting to dispatch in getServerSideProps, the State refuses to change. Could it be due to the Redux-Next-Wrapper?

I'm facing an issue where the Redux Store does not change when I dispatch in getServerSideProps. Even though I can see the changes in console log after dispatch, the store appears as an empty array when the page loads. Why are these changes not taking ...

What could be the reason behind Strapi v4 only displaying the initial 25 articles? Discussing Next.js and React

I've encountered a peculiar bug while working with Strapi v4. The technology stack being used is React and Next.js I've set up a dynamic pagination system with the format /page/[slug]. It's functioning almost perfectly, except for one majo ...

The visibility of the Google +1 button is lost during the partial postback process in ASP.NET

When trying to implement the Google Plus One button using AddThis on one of our localized pages, we encountered a strange issue. Despite retrieving data from the backend (let's assume a database), the plus button was not loading during an AJAX based p ...

Dynamically adjust row height in AG Grid within an Angular application based on the visibility of other columns

My current AG-Grid version is 21.2.1, and I am unable to upgrade it for certain reasons. I have successfully implemented wrapping cell content to ensure all content is visible. Additionally, I have buttons in my application to toggle the visibility of col ...

The getElementByID function functions properly in Firefox but does encounter issues in Internet Explorer and Chrome

function switchVideo() { let selectedIndex = document.myvid1.vid_select.selectedIndex; let videoSelect = document.myvid1.vid_select.options[selectedIndex].value; document.getElementById("video").src = videoSelect; } <form name="myvid1"> <s ...

Is it possible to nullify an object and utilize nullish coalescing for handling potentially undefined constants?

In my development work with React, I often utilize a props object structured like this: const props: { id: number, name?: string} = { id: 1 }; // 'name' property not defined const { id, name } = props; // the 'name' constant is now fore ...

Utilizing Radio buttons for validation in react-hook-form

After creating a form with radio buttons and implementing validation using React Hook Form, I encountered an issue where the console always displayed "on" regardless of the selected radio button. <div className=""> <label ...

Ways to navigate through a webpage without encountering any overflow issues

My window is too small to scroll, but I still need the ability to do so. Is it possible to scroll even when the height of the container is not large enough to display the scrollbar? Below is the code I am using to achieve scrolling: setTimeout(function() ...

Having trouble getting undefined values for keys while attempting to retrieve all the data from Firebase DB with Angular

Currently, I have code that is fetching records from the Firebase database using both Angular and Ionic. The code functions properly, but it does not provide me with the keys for each record. Instead, it returns 'undefined'. I have researched s ...

Exploration into the Working Environments of JavaScript and Python

After executing JavaScript code (shown in the top-half) on link1 and python code (shown in the bottom-half) on link2, the diagram below was generated. My inquiry: I noticed that names foo & bar are already present in the global frame (highlighted in ...

Choosing between radio buttons either horizontally or vertically within a table

Here is the markup I am working with: <table> <tr> <td><input type="radio" name="radio"></td> <td><input type="radio" name="radio"></td> <td><input type="radio" name="radio"></ ...

Having trouble capturing screenshots with PuppeteerJS?

I've encountered an issue while working with Puppeteer to capture screenshots from a provided URL. The code I have below doesn't seem to be functioning properly. It keeps showing the error message: [0] Error: Protocol error (Emulation.setDeviceM ...

Guide on associating user IDs with user objects

I am currently working on adding a "pin this profile" functionality to my website. I have successfully gathered an array of user IDs for the profiles I want to pin, but I am facing difficulties with pushing these IDs to the top of the list of profiles. My ...

"Scrolling with Bootstrap Scroll Spy is causing incorrect sections to be

Can anyone help me with my issue regarding Bootstrap scrollspy settings? It seems to be highlighting the wrong div id, always the last one. Here is the code snippet: Content: <body style="heigt: 100%" data-spy="scroll" data-target="#side-menu"> ...

Tips for retrieving the count from HTML using JavaScript:

I need to determine the count of list items in an unordered list within dir-pagination-controls. How can I achieve this using JavaScript? <dir-pagination-controls min-size="1" direction-links="true" boundary-links="true" class="pull-right ng-isolate- ...

Utilizing AngularJS for Showcasing JSON Information Using Ng-Repeat and Ng-Factory

As a newcomer to Javascript and Angular, I am currently working on integrating AngularJS into my website. Despite watching tutorials from CodeSchool, Egghead, and others, I seem to be stuck at the very beginning. My issue lies in retrieving JSON data from ...

Sharing environment variables in gulpfile with other JavaScript files outside NODE_ENV

Is it possible to pass a variable other than NODE_ENV from the gulpfile.js to another javascript file? gulpfile.js // Not related to NODE_ENV! let isDevelopment = true; somejsfile.js /* I need to access "isDevelopment" from the gulpfile.js... For the ...

Just a quick inquiry regarding adding new line characters in JSON to be used in

After encountering an issue with a JSON file in my JavaScript application where it would not print new lines when viewed on the console, I am at a loss for a solution. The contents of my JSON file are as follows: [ { "id": "71046" ...

How can we detect if the pressing of an "Enter" key was triggered by an Angular Material autocomplete feature?

Currently, I have incorporated an Angular Material Autocomplete feature into my search bar. When a user types in their query and presses the Enter key, the search is executed as expected. Nevertheless, if the user decides to select one of the autocomplete ...