skip to Main Content

For technical reasons detailed here (CJS) I need to import a function and then reexport it immediately. The linked doc explains how to do this in CJS, but how can I do the same in ES Modules?

My code below shows an error:

import { foo } from './foo';
import { bar } from './bar';

export const foo = foo;
export const bar = bar;

Error: Parsing error: Identifier 'foo' has already been declared

For reference, Common JS code that works and that I am trying to convert to ESM:

const foo = require('./foo');
const bar = require('./bar');
exports.foo = foo.foo;
exports.bar = bar.bar;

2

Answers


  1. You can use the export keyword:

    export { foo } from './foo'
    

    Check https://basarat.gitbook.io/typescript/main-1/barrel

    Login or Signup to reply.
  2. If you want to reexport:

    export { foo } from './foo'
    

    If you want to import and then export:

    import { foo } from './foo'
    doWhatever(foo)
    export { foo }
    

    If you want import and make export const with same name:

    import { foo as importedFoo } from './foo'
    export const foo = doWhatever(importedFoo)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search