dmonad / lib0

Monorepo of isomorphic utility functions
MIT License
347 stars 62 forks source link

ES Module error when importing types #21

Closed robindiddams closed 3 years ago

robindiddams commented 3 years ago

Describe the bug I am unable to import and use the generated types because this is an es module, so I can import the cjs files fine from dist but then I don't get the types. Is there a way to use the typescript d.ts files at all?

To Reproduce

import { createEncoder } from 'lib0/encoding';

const encoder = createEncoder();

console.log(encoder);

Save as index.ts.

  1. tsc index.ts
  2. node dist/index.ts this results in:
    
    internal/modules/cjs/loader.js:1092
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/robindiddams/work/lib0test/node_modules/lib0/encoding.js require() of ES modules is not supported.


according to [this post on discuss.yjs.dev](https://discuss.yjs.dev/t/error-when-instantiating-awarenessprotocol/324) im supposed to do it like this:
```javascript
const { createEncoder } = require('lib0/dist/encoding.cjs');

but then I lose my type definitions šŸ˜¢ .

Expected behavior I expect to be able to use the types declarations in a typescript nodejs app.

Screenshots I've made a repo with the code if you want to look more https://github.com/Robindiddams/lib0test

Environment Information

Additional context Using in a nodejs server, so not running in the background

dmonad commented 3 years ago

Hi @Robindiddams,

I recommend to create aliases for the imports. Using webpack aliases: https://webpack.js.org/configuration/resolve/#resolve-alias

I created a simple rollup extension that renames lib0/[name].js to lib0/dist/[name].cjs: https://github.com/yjs/yjs/blob/main/rollup.config.js

robindiddams commented 3 years ago

Thanks for the fast reply, since this is node server I wont be using webpack, but I think I get what what you're doing, I should be able to do the same, thanks šŸ»