dmonad / lib0

Monorepo of isomorphic utility functions

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ES Module error when importing types

robindiddams opened this issue · comments

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 im supposed to do it like this:

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

  • Nodejs version: v14.9.0
  • Typescript version: 4.1.3
  • macos 11.1

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

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

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 🍻