mobily/ts-belt

Import into typescript project whose option module:nodenext doesn't work

Closed this issue ยท 7 comments

First of all, I want to say that I really like ts-belt utilities and really wanted to make it work with my current project.


import { A, D, O, pipe } from '@mobily/ts-belt';
         ^
SyntaxError: Named export 'A' not found. The requested module '@mobily/ts-belt' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from '@mobily/ts-belt';
const { A, D, O, pipe } = pkg;

Issue:

  • When import into a project whose module:nodenext, ts-belt is resolved as a esm module and redirected to dist/esm folder. However, the files of this folder still have .js extension and the package.json does't contain type:module option, which makes node assumes that it is trying to import a CommonJS module and try to resolve the import as such.
  • Furthermore, appying the above fix doesn't solve the problem, as it results in this error:
^^^^^^

SyntaxError: Cannot use import statement outside a module

Since all files inside esm are still understood as commonjs files, the import syntax of esm still doesn't work.


Proposed fix:

  • Add a build step that add additional option "type":"module" to dist/esm/package.json
  • The above option will break esm folder, as node really doesn't understand import without file extension. Typescript compiler also won't add extensions by default. This may require manually updating ts files with import to include extension instead, for example import * from 'Require' to import * from 'Require/index.js'.

hello @khaiquangnguyen ๐Ÿ‘‹ could you provide a reproduction repo?

Sure.
https://github.com/khaiquangnguyen/tsbelt-nodenext
Here is it.
npm run build and then npm run start to see the error.
So after a couple of testings, it only have issues with nodenext module. both esnext and node16 seems to work fine. This is a bit of an edge case but official node and typescript have recommended nodenext as the path forward, so i think we should try to support this if possible.

I ran into the same issue today when using ts-belt with ESM and TypeScript. I haven't been able to find a workaround yet.

same here

import { D } from '@mobily/ts-belt';
         ^
SyntaxError: Named export 'D' not found. The requested module '@mobily/ts-belt' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from '@mobily/ts-belt';
const { D } = pkg;

@mobily I can take a look at this if you are too busy at the moment.

@khaiquangnguyen @tgillus @Talent30 the issue has been fixed in v4.0.0-rc.1 ๐Ÿš€

@mobily That's awesome. I appreciate your work on this library.