TypeScript-Handbook icon indicating copy to clipboard operation
TypeScript-Handbook copied to clipboard

`export =` also works with `import * as`

Open OliverJAsh opened this issue 5 years ago • 1 comments

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

OliverJAsh avatar Jan 06 '20 13:01 OliverJAsh

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

DanielRose avatar Feb 17 '20 16:02 DanielRose