Skip to content
This repository has been archived by the owner on Oct 12, 2022. It is now read-only.

export = also works with import * as #1278

Open
OliverJAsh opened this issue Jan 6, 2020 · 1 comment
Open

export = also works with import * as #1278

OliverJAsh opened this issue Jan 6, 2020 · 1 comment

Comments

@OliverJAsh
Copy link
Contributor

OliverJAsh commented Jan 6, 2020

When exporting a module using export =, TypeScript-specific import module = require("module") must be used to import the module.

https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require

I'm confused about this statement, because import * as module from 'module' also works, right?

/cc @DanielRosenwasser

@DanielRose
Copy link

It is a bit confusing, because "must" in this case means "really should (but we'll often fix your mistake if you do it wrong)".

The code import * as module from 'module' actually means "import the namespace in 'module', and refer to that namespace as module in the file". Such a namespace is not callable/constructable according to the ECMAscript spec. However, lots of TypeScript code out there uses this incorrect code.

So if your module target is CommonJS, TypeScript will fix it for you, as if you wrote import module = require("module"). If your module is an ES module, however, TypeScript won't fix it for you, and the code will fail. So as the NodeJS ecosystem is slowly moving to ES modules, at some point your "working" code could start failing if you use the incorrect syntax.

Not that in the section below it, you can see what will be generated by the TypeScript compiler, depending on the module target (https://www.typescriptlang.org/docs/handbook/modules.html#code-generation-for-modules).

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants