The version 13.2 of Node.js allows ESM modules and a new package.json
field, called exports
, to select and rewrite exported files.
Before 13.2, I was importing files from the dist
folder of my library with:
import myfile from 'mylibrary/dist/myfile'
With 13.2, I added this to my package.json
:
exports: {
"./": "./dist/"
}
And tried to import files with:
import myfile from 'mylibrary/myfile'
But Typescript raises the 2307 error, saying that module is not found.
It is an upcoming feature of Typescript 4.5 which soon should be available:
// package.json
{
"name": "my-package",
"type": "module",
"exports": {
".": {
// Entry-point for `import "my-package"` in ESM
"import": "./esm/index.js",
// Entry-point for `require("my-package") in CJS
"require": "./commonjs/index.cjs",
// Entry-point for TypeScript resolution
"types": "./types/index.d.ts"
},
},
// CJS fall-back for older versions of Node.js
"main": "./commonjs/index.cjs",
// Fall-back for older versions of TypeScript
"types": "./types/index.d.ts"
}
For now, I've managed to utilize typesVersions
:
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": "./dist/index.js",
"./svg": "./dist/svg.js",
"./html": "./dist/html.js",
"./package.json": "./package.json"
},
"typesVersions": {
"*": {
"svg": ["dist/svg.d.ts"],
"html": ["dist/html.d.ts"]
}
}
There is some work required on the TypeScript side to support this. The feature is tracked here in github. In that link there are also some workarounds listed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With