Search code examples
javascriptnode.jses6-modules

Named export with same name as existing variable in Javascript ES Modules


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;

Solution

  • 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)