Description
I'd like to propose the following syntax for importing named exports from CommonJS modules in TypeScript:
import { readFile } = require('fs');
When transpiling to CommonJS the above would become:
const { readFile } = require('fs');
And when transpiling to ES modules it would become:
import _fs from 'fs';
const { readFile } = _fs;
Thinking purely in terms of what this means in an ES modules world, the import x = require('x')
is identical to import x from 'x'
while import { x } = require('x')
is a destructuring of the default export in the ES module semantics.
Such a syntax would offer a replacement for the import { fs } from 'fs'
which will not be ever supported in NodeJS since a CommonJS module is represented by the namespace object ModuleNamespace { default: fs }
. So such a syntax makes it clear that this is a TypeScript-specific convenience during the transition period (many years yet) into ES modules.
Having this alternative in place would allow TypeScript to then have the same module semantics between outputting ES modules and CommonJS modules on this working subset, without losing the feature expressivity of named exports for CommonJS modules.
Related: #17556