-
-
Couldn't load subscription status.
- Fork 82
Description
node16 from ESM: type errors
Using the packages from Deno with TypeScript leads to type errors, but these errors can also be observed with tsc and Node.JS when using the new node16 module resolution:
$ npm i postcss-nesting
$ echo '{"type": "module"}' > package.json
$ echo "import postcssNesting from 'postcss-nesting'; postcssNesting();" > example.ts
$ tsc example.ts --moduleResolution node16 --lib es2020
example.ts:1:47 - error TS2349: This expression is not callable.
Type 'typeof import("/tmp/example/node_modules/postcss-nesting/dist/index")' has no call signatures.
1 import postcssNesting from 'postcss-nesting'; postcssNesting();
~~~~~~~~~~~~~~
node16 from CJS: runtime error
$ npm i postcss-nesting
$ echo '{"type": "commonjs"}' > package.json
$ echo "import postcssNesting from 'postcss-nesting'; postcssNesting();" > example.ts
$ tsc example.ts --moduleResolution node16 --lib es2020
$ node example.js
/tmp/example/example.js:4
(0, postcss_nesting_1.default)();
^
TypeError: (0 , postcss_nesting_1.default) is not a function
at Object.<anonymous> (/tmp/example/example.js:4:31)
at Module._compile (node:internal/modules/cjs/loader:1254:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
at Module.load (node:internal/modules/cjs/loader:1117:32)
at Module._load (node:internal/modules/cjs/loader:958:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
Node.js v18.14.2
What to do
As Are the types wrong? explains:
A golden rule of declaration files is that if they represent a module—that is, if they use import or export at the top level—they must represent exactly one JavaScript file. They especially cannot represent JavaScript files of two different module formats.
So the exports like the following are wrong since they provide one types for both ESM and CJS:
postcss-plugins/plugins/postcss-nesting/package.json
Lines 39 to 46 in aaf8807
| "exports": { | |
| ".": { | |
| "types": "./dist/index.d.ts", | |
| "import": "./dist/index.mjs", | |
| "require": "./dist/index.cjs", | |
| "default": "./dist/index.mjs" | |
| } | |
| }, |
Unfortunately @rollup/plugin-typescript like apparently most other build tools does not supporting correctly emitting different type definitions for ESM and CJS.
(Note that the Are the types wrong? website currently wrongly doesn't report the node16 From CJS problem since it doesn't yet perform type checking).