Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New package.json `exports` field not working with TypeScript

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.

like image 454
Lucas Willems Avatar asked Nov 22 '19 08:11

Lucas Willems


2 Answers

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"]
    }
  }
like image 170
Igor Sukharev Avatar answered Nov 16 '22 07:11

Igor Sukharev


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.

like image 6
Ivan Sanz Carasa Avatar answered Nov 16 '22 08:11

Ivan Sanz Carasa