david_adler
david_adler

Reputation: 11002

Typescript export const foo vs export default { foo }

Are the three export options exactly equivalent?

// foo.ts
export const foo = () => {}
// foo.ts
const foo = () => {}
export default { foo }
// foo.ts
const foo = () => {}
export { foo }

Disclaimer: I know that import { foo } from './foo' will work just the same in all scenarios but are there any nuances?

Particularly interested in any nuances that might occur when having a mixed ts and js codebase.

Using tsconfig "module": "CommonJS", nodejs v14 and typescript 4.2.4

Upvotes: 4

Views: 5088

Answers (1)

user16435030
user16435030

Reputation:

The short answer is no they're not the same, they have different syntax, but let's be serious.

export const foo = () => {}

...

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.foo = void 0;
var foo = function () { };
exports.foo = foo;

Is what that compiles to using commonjs and es5 as target.

const foo = () => {}
export default { foo }

...

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var foo = function () { };
exports.default = { foo: foo };

Is what that compiles to.

const foo = () => {}
export { foo }

...

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.foo = void 0;
var foo = function () { };
exports.foo = foo;

Is what that compiles to.

Along with that it should also be noted that using:

export { foo }

Can only be imported using:

import {foo} from './foo'

While using:

export default { foo }

Can only be imported using:

import whatever from './foo'

// use whatever.foo

Upvotes: 3

Related Questions