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

Angular unburdened by jquery

I need help converting the following code from using JQuery to only Angular. I am unsure of how to accomplish this. Thank you! var startProduct = $("#product-overview").position().top - 60; var endProduct = $("#global-features").position().t ...

Ways to transfer information among Angular's services and components?

Exploring the Real-Time Binding of Data Between Services and Components. Consider the scenario where isAuthenticated is a public variable within an Authentication service affecting a component's view. How can one subscribe to the changes in the isAut ...

I'm having trouble getting my code to work with axios in Vue.js. How can I fix this issue

I am trying to use axios.get to retrieve data from my database, but I encountered an error. Below is my code in store.js export default new Vuex.Store({ state: { test: null }, mutations: { testt(state, payload) { state.test = payloa ...

Leveraging JavaScript within the Selenium JavaScript Executor

I am trying to check if the required text is visible on the page, but I am unable to use the gettext() method from Selenium WebDriver due to a permission exception. As a workaround, I have created a JavaScript script to compare the text. String scriptToE ...

Converting a string to a JSON array with Jackson in RESTful APIs

As I delve into the world of JSON and REST, I find myself testing a REST API that returns strings in the following format: [{ "Supervisor_UniqueName": "adavis", "Active": "true", "DefaultCurrency_UniqueName": "USD", "arches_type": "x-zensa ...

Extract table information from MuiDataTable

I am having trouble retrieving the row data from MuiDataTable. When I try to set the index from the onRowSelectionChange function to a state, it causes my checkbox animation to stop working. Below is how my options are currently configured: const option ...

Creating a Component and Programmatically Returning a Value in Vue.js: A Step-by-Step Guide

Could you assist me in solving my issue? I am looking to develop a customized plugin for my project so that my team and I can easily implement an alert component without having to design the dialog box repeatedly on every page and vuejs file. My objective ...

Sending data between two elements when a jQuery event is triggered

As a JavaScript beginner, I am facing an issue where I need to push data from an h1 tag to a textarea. My website is built using WooCommerce and when a visitor clicks on a product, a chat box with the product title opens. Currently, I have successfully p ...

Compilation failure due to Typescript initialization issue

Encountering a TypeScript error in my IntelliJ-Idea 2017.1.1 IDE I have enabled JavaScript, NodeJS, and TypeScript Compiler. I have exhausted all solutions but the issue persists, perhaps I am missing something. Error: Initialization error (typescript ...

Is it better to deploy a JS app to the browser, or should I consider using nw.js

Is there a tool available for developing a javascript application that can be deployed as either a browser-based or native app using nwjs or Atom Electron? It should only utilize browser-compatible features and not node's native features. Maybe th ...

Utilizing Puppeteer to Navigate and Interact with Elements Sharing Identical Class Names

I am new to Puppeteer and NodeJs, and I am attempting to scrape a specific website with multiple posts that contain a List element. Clicking on the List element loads the comment section. My question is: I want to click on all the list elements (since th ...

Having trouble sending an array's JSON data to a web service using Angular

I am working with a table where each cell in the rows contains form fields. The table also has two buttons: one button adds a new row to the table, and the other sends all the rows. Below is the code snippet for adding new blank rows: $scope.attributes = ...

Determine the number of network requests being made on a webpage

In my quest to develop a universal method using selenium, I am seeking a way to ensure that all background network activities, including Ajax, Angular, and API calls, have completed. While I am aware of the option to determine the number of active Ajax cal ...

Is there a way to create a timed fadeIn and fadeOut effect for a div using HTML and CSS?

I have a single div that initially displays text, and I want it to fade out after a specific time so that another div will then fade in. However, my attempt at coding this transition is not producing the desired result: $(function() { $(".preloa ...

Utilize only the necessary components from firebase-admin in Cloud Functions with Typescript

When I looked at my transpiled code from cloud functions, I noticed the following TypeScript import: import { auth, firestore } from 'firebase-admin'; It gets transpiled to: const firebase_admin_1 = require("firebase-admin"); Upon further exa ...

React and Material-Ui utilize class definitions in .js files, which are then passed as strings to components

I am attempting to define a class within my .js file in order to utilize the material-ui theme object and pass it as a string to a component since the component's prop only accepts strings. Unfortunately, the React-Dropzone import does not accept a cl ...

What is the specific character code assigned to the "Enter" key on a

Check out this code snippet: http://jsfiddle.net/YttKb/ In my javascript, I am trying to add a new line of text using utf-8 coding. Which character should I use to make a new line? It seems like \n only creates a line break, not a new line of text. ...

Tips for incorporating a hashbang into a JavaScript file that is executable without compromising browser compatibility

Is it possible to run code like this in both Node.js and the browser? #! /usr/local/bin/node console.log("Hello world") I have a script that I currently run locally in Node.js, but now I want to also execute it in the browser without having to modify it ...

Recalling the use of jquery toggle throughout the website?

I have successfully implemented a button to hide and unhide a lengthy menu with a click, but I am struggling to make the menu state persistent across multiple pages. I would like the last toggle action by the visitor to be remembered. Any suggestions on ho ...

The issue with Jquery Ajax is that it fails to properly update MySQL values

Greetings, I am currently attempting to utilize AJAX to update data from a modal form. Although I submit the data successfully, it does not reflect the changes in the database. Here is my JavaScript code: <script> jQuery(document).ready(functio ...