MikeMcl / decimal.js

An arbitrary-precision Decimal type for JavaScript
http://mikemcl.github.io/decimal.js
MIT License
6.35k stars 480 forks source link

Fix typescript 4.7 / node16 import/type resolution #201

Closed ml1nk closed 2 years ago

ml1nk commented 2 years ago

Typescript 4.7 / node16 uses decimal.js even is type is "module" because it does not find an export and uses main. If you directly include decimal.mjs then it tries to include decimal.d.mts and fails (no typing).

jaydenseric commented 2 years ago

Note that this would break for the Node.js runtime existing deep imports, e.g:

import Decimal from "decimal.js/decimal.mjs";

It's also best practice to export package.json because some tools need to be able to require or import it.

ml1nk commented 2 years ago

You are right, i haven't thought about it. I can add both cases if merge is possible after that.

MikeMcl commented 2 years ago

Any feedback on the following?

"exports": {
  ".": {
    "types": "./decimal.d.ts",
    "import": "./decimal.mjs",
    "require": "./decimal.js"
  },
  "./decimal.mjs": "./decimal.mjs",
  "./decimal.js": "./decimal.js",
  "./package.json": "./package.json"
}
ml1nk commented 2 years ago

Looks good to me.

jaydenseric commented 2 years ago

What about https://github.com/MikeMcl/decimal.js/blob/master/decimal.global.d.ts , how is that supposed to be used/accessed?

jaydenseric commented 2 years ago

Do you need to do:

"exports": {
  ".": {
    "types": "./decimal.d.ts",
    "import": "./decimal.mjs",
    "require": "./decimal.js"
  },
  "./decimal.mjs": {
    "types": "./decimal.d.ts",
    "default": "./decimal.mjs"
  },
  "./decimal.js": {
    "types": "./decimal.d.ts",
    "default": "./decimal.js"
  },
  "./package.json": "./package.json"
}
ml1nk commented 2 years ago
 "./decimal.js": {
    "types": "./decimal.d.ts",
    "default": "./decimal.js"
  },

I think types here is not needed, as .js => d.ts is implicit.

  "./decimal.mjs": {
    "types": "./decimal.d.ts",
    "default": "./decimal.mjs"
  },

As mjs is automatically used when "." has require and import properties, importing ./decimal.mjs and ./decimal.js directly is deprecated. As such adding typing is not needed, as you shouldn't use it anymore and it is only added for backward compatibility (!= usage with typescript).

What about https://github.com/MikeMcl/decimal.js/blob/master/decimal.global.d.ts , how is that supposed to be used/accessed?

I'm also interested in the answer, i have no idea when you would import this file directly.

MikeMcl commented 2 years ago

What about https://github.com/MikeMcl/decimal.js/blob/master/decimal.global.d.ts , how is that supposed to be used/accessed?

It's for use in the browser when the typings need to be available in the global scope.

I think it's a case of setting the compiler options accordingly or adding a directive such as the following to the file which wants to use those typings:

/// <reference types="decimal.global.d.ts" />