Open
Description
@vmx had reported a problem with default export not passing a type check
multiformats/js-multiformats#66 (comment)
import CID from 'multiformats/cid import raw from 'multiformats/codecs/rawIn commonjs modules, these kind of imports don't work (same with and without this PR). When I do
const CID = require('multiformats/cid')I get
error TS2339: Property 'parse' does not exist on type 'typeof import("/some/path/js-multiformats/dist/types/cid")'
I also tried adding
/** * @typedef {import('multiformats/cid')} CID */
but that didn't help either.
The problem here is that TS expects CID = require('multiformats/cid').default
instead. Here is how they put it:
By default (with esModuleInterop false or not set) TypeScript treats CommonJS/AMD/UMD modules similar to ES6 modules. In doing this, there are two parts in particular which turned out to be flawed assumptions:
- a namespace import like import * as moment from "moment" acts the same as const moment = require("moment")
- a default import like import moment from "moment" acts the same as const moment = require("moment").default
This mis-match causes these two issues:
- the ES6 modules spec states that a namespace import (import * as x) can only be an object, by having TypeScript treating it the same as = require("x") then TypeScript allowed for the import to be treated as a function and be callable. This breaks the spec’s recommendations.
- while accurate to the ES6 modules spec, most libraries with CommonJS/AMD/UMD modules didn’t conform as strictly as TypeScript’s implementation.
In theory esModuleInterop
option should fix this, but that does not seem to work in practice.
I think we need to either:
- Change how ipjs generates .cjs files, which is either:
- Default export goes into
exports.default =
- Or we do
module.exports = thing; thing.default = thing;
(I don't like this option) - Just use and support named exports (I'm sure anything else would break some assumption some other tool makes)
- Make type generation a job of ipjs instead. And generate two sets of types (this will probably also address Publishing from
dist
breaks "types" and "typeVersions" fields of package.json #10)- From and for ES modules
- From and for cjs modules
Metadata
Metadata
Assignees
Labels
No labels