microsoft / TypeScript-Handbook

Deprecated, please use the TypeScript-Website repo instead
https://github.com/microsoft/TypeScript-Website
Apache License 2.0
4.88k stars 1.13k forks source link

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

Open OliverJAsh opened 4 years ago

OliverJAsh commented 4 years ago

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 commented 4 years ago

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