This has been reported before (#1200) and marked as fixed, but unfortunately it's still not working in CommonJS projects.
Typescript throws this error when compiling:
index.ts:1:25 - error TS1479: The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import("superstruct")' call instead.
Minimal repro
package.json
{
"name": "repro",
"version": "1.0.0",
"license": "MIT",
"devDependencies": {
"typescript": "5.7.2"
},
"dependencies": {
"superstruct": "2.0.2"
}
}
tsconfig.json
{
"compilerOptions": {
"module": "Node16",
}
}
index.ts
import superstruct from 'superstruct';
Solution
From looking at other packages and skimming through the typescript docs, it looks like the way to fix this is to replace the index.d.ts file with a pair of index.d.mts and index.d.cts files. How you'd generate the latter is a bit unclear. unbuild seems to be able to do so, and it uses rollup too.
Once you have generated a pair of index.d.{cts,mts} files you can either:
- Remove the "types" field from your
package.json to let typescript automatically resolve each index.{cjs,mjs} file to the corresponding index.d.{cts,mts} file.
- Or, add something like this to your
package.json:
"exports": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
This has been reported before (#1200) and marked as fixed, but unfortunately it's still not working in CommonJS projects.
Typescript throws this error when compiling:
Minimal repro
package.json
{ "name": "repro", "version": "1.0.0", "license": "MIT", "devDependencies": { "typescript": "5.7.2" }, "dependencies": { "superstruct": "2.0.2" } }tsconfig.json
{ "compilerOptions": { "module": "Node16", } }index.ts
Solution
From looking at other packages and skimming through the typescript docs, it looks like the way to fix this is to replace the
index.d.tsfile with a pair ofindex.d.mtsandindex.d.ctsfiles. How you'd generate the latter is a bit unclear.unbuildseems to be able to do so, and it uses rollup too.Once you have generated a pair of
index.d.{cts,mts}files you can either:package.jsonto let typescript automatically resolve eachindex.{cjs,mjs}file to the correspondingindex.d.{cts,mts}file.package.json: