mobily / ts-belt

🔧 Fast, modern, and practical utility library for FP in TypeScript.
https://mobily.github.io/ts-belt
MIT License
1.11k stars 31 forks source link

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

Closed khaiquangnguyen closed 1 year ago

khaiquangnguyen commented 2 years ago

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:

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'`. 
mobily commented 2 years ago

hello @khaiquangnguyen 👋 could you provide a reproduction repo?

khaiquangnguyen commented 2 years ago

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.

tgillus commented 1 year ago

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.

Talent30 commented 1 year ago

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;
khaiquangnguyen commented 1 year ago

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

mobily commented 1 year ago

@khaiquangnguyen @tgillus @Talent30 the issue has been fixed in v4.0.0-rc.1 🚀

tgillus commented 1 year ago

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