Export all except those from the module in ESM

Suppose I have two imports containing numerous named exports, too many to list individually, and I need to reexport them while excluding a few due to naming conflicts.

For example, consider the following two files:

foo.js:

export const a = 1;
export const b = 2;

bar.js:

export const b = 1;
export const c = 3;

If I want to combine and reexport all of them using CommonJS, I can achieve this with the following approach:

/* use rest destructuring to store everything except "b" in variable "foo" */
const { b, ...foo } = require("./foo"); 
const bar = require("./bar");

module.exports = {
    ...foo,
    ...bar
};

Although in my TypeScript project, the closest solution I found was using export = { ... } in a similar manner:

import * as foo from "./foo";
import * as bar from "./bar";

const { b, ...foo2 } = foo;

export = {
    ...foo2,
    ...bar,
};

However, I believe this would output a file with CommonJS module.exports instead of a proper ESM module (likely requiring esModuleInterop). Furthermore, it's specific to TypeScript and not applicable when working with pure JavaScript.

Is there a way to achieve this using ESM import / export syntax instead?

Answer №1

Is it possible to achieve this using ESM import/export instead?

Unfortunately, pure standard ESM does not offer a way to do this without explicitly listing the named exports. In ESM, there is no concept of "rest" when it comes to importing or exporting.

One alternative approach could be exporting an object with properties for `a`, `b`, and `c`, but this method is quite different from re-exporting named exports. It would not create a live binding, and the syntax for importing its parts differs from importing named exports (unless you utilize build-time tools like TypeScript or bundlers).

For reference, here's how you could implement this approach (similar to the TypeScript version you provided at the end), although it may not align with your requirements:

reexport.js:

import * as foo from "./foo.js";
import * as bar from "./bar.js";

const { b, ...restOfFoo } = foo;
export default {
    ...restOfFoo,
    ...bar,
};

To use this setup:

// Import the object (which is the default export)
import stuff from "./reexport.js";

// Destructure into local variables (if desired)
const { a, b, c } = stuff;

// Access and utilize the imported values...
console.log(a, b, c);

This implementation complies with standard ESM specifications.

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

Prevent button interaction until completion of modal animation using Bootstrap 4

I have incorporated a Bootstrap 4 modal in my website to display a large navigation menu. The navigation is triggered by a toggle button with a CSS animation that transforms a hamburger icon into an X. However, I encountered an issue where if the button i ...

Iterating over an array of numbers in AngularJS

I have an array of numbers $scope.N = [1,2,3,4]. I want to loop through this array in my HTML code using ng-repeat, similar to the example with JSON ng-repeat. <div ng-repeat="num in N"> {{num}} </div> How can I achieve this with a ...

Tips on preventing a nested loop's inner ng-repeat from updating when the array undergoes changes

My current challenge involves working with an array of events, each event has teams participating in it. Although these objects are related, they are not properties of each other. I am attempting to loop through every event and display the teams participa ...

What could be causing the <img src= ' '/> tag to malfunction in Express?

While learning about HTML, I noticed that simply using img src="...." worked fine. However, when working with Express, the same code did not work! The documentation mentioned that I needed to place the images in a folder named public, require(&ap ...

Creating a custom decision tree in Angular/JS/TypeScript: A step-by-step guide

My current project involves designing a user interface that enables users to develop a decision tree through drag-and-drop functionality. I am considering utilizing GoJS, as showcased in this sample: GoJS IVR Tree. However, I am facing challenges in figuri ...

Developing a discriminated union by utilizing the attribute names from a different type

In my quest to create a unique generic type, I am experimenting with extracting property names and types from a given type to create a discriminated union type. Take for example: type FooBar = { foo: string; bar: number; }; This would translate t ...

What is the best way to indicate the selected item in the Menu List using Material UI React?

I am attempting to dynamically style the menu list items by toggling the selected prop between true and false. In order to achieve this, I am utilizing the onClick method to capture the event.target.name, update the state of the corresponding value associ ...

Retrieving a specific id from a meteor-rendered template to access a collection field

UPDATE: I have recently included additional code for clarification, marked as * NEW *. To explain the functionality of this code - it involves inputting a series of data into a collection named posts. The displayed output on the postsList template occurs w ...

Looking for a method to incorporate an onclick function into a column for renderCell within the MUI Datagrid. Any suggestions?

I'm currently developing a react application and utilizing the MUI Datagrid to present some data. I have incorporated a rendercell to insert an edit icon which should trigger a pop-up modal when clicked. Below is the column setup. export const specifi ...

Updating the state across various components proves to be a challenge when relying on both the context API and higher order components

I have been working on updating the application state using the context API instead of using Redux, as I do not require all of its features and want to avoid prop drilling. With TypeScript, I created a global context and a higher-order component (HOC) wrap ...

Most effective method to verify if mutation observer meets specific criteria

I have set up a mutation observer to monitor changes in the page load. Specifically, I am interested in detecting the moment when a particular element is loaded or exists. This element can be identified by its classname, let's say it's called foo ...

The error message "TypeScript reflect-metadata Cannot find name 'Symbol'" indicates that TypeScript is unable to locate

While browsing through http://www.typescriptlang.org/docs/handbook/decorators.html#class-decorators, I encountered an issue where it could not find the Symbol. I was unsure whether this is related to the usage of reflect-metadata or if it was previously in ...

Creating image gallery with navigation arrows in JS/jQuery to loop through array of thumbnails

I am relatively new to working with arrays, and I have been exploring ways to use them in controlling the positions of thumbnails when navigating through a series of images using next or previous buttons. My goal is to make the thumbs loop seamlessly whene ...

Looking to adjust the height of a foreignObject element within an SVG?

Looking to dynamically change the height of a foreignObject within an SVG, while also needing HTML elements inside it (working with ngx-graph). <foreignObject x="1" y="1" width="335" [height]="foreignObjHeight(node.Dat ...

Deactivating Cluetip tool tips and adjusting the height limit in JQuery

How can I momentarily turn off the hints? I have seen references to being able to do so on the website and in this forum, but I am having trouble locating the command to disable them. I just need to temporarily deactivate them and then enable them again. ...

What is the method for showcasing login errors and prompting users to fill in all fields simultaneously on a page with PHP?

As I develop a PHP login page, I am implementing a system where users need to enter a username and password to access the platform. One query that arises is: How can I dynamically display an 'Invalid username or password' error message on the s ...

What is the syntax for using typeof with anonymous types in TypeScript?

After reading an article, I'm still trying to grasp the concept of using typeof in TypeScript for real-world applications. I understand it's related to anonymous types, but could someone provide a practical example of how it can be used? Appreci ...

Guide on configuring href tags in single-page JavaScript/HTML5 apps

After developing a "small" single page web application using python/django/backbone, similar to a basic Todo List app, a challenge arose regarding maintaining SEO-friendly href attributes without forcing users' browsers to reload the entire app at a n ...

"Using conditional statements to check for specific value ranges and properly handling cases where the result is undefined

Currently, I am working on a function that prompts the user to input a number and then displays a calculated score after they click a button. The score is based on the value entered by the user. While constructing this feature, I have pondered whether IF ...

Delete specific rows within a grid view exclusively on the user's browser

I need to implement a feature where users can remove individual rows from a gridview on the screen without affecting the database. The gridview is populated based on the index selected from a dropdown list. Each row in the gridview should have a remove bu ...