DonJayamanne/typescript-notebook

Error on import ES module

Opened this issue · 1 comments

Cell with this content:

const lib = await import('./lib.mjs');

returns error:

Error [ERR_REQUIRE_ESM]: require() of ES Module /home/username/project/lib.mjs not supported.
Instead change the require of /home/username/project/lib.mjs to a dynamic import() which is available in all CommonJS modules.
    at _._load (/home/username/project/index.js:2:115372)
    at  [1, 0]

I think notebook interpreter replace import to require as is. This results in an error.

I tried to hack around this via

const lib = await (new Function('id', 'return import(id)'))('./lib.mjs');

but that results in

TypeError [ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING]: A dynamic import callback was not specified.
    at new NodeError (node:internal/errors:399:5)
    at importModuleDynamicallyCallback (node:internal/modules/esm/utils:89:9)
    at eval (eval at  ( [1, 98]), :3:1)
    at  [1, 42]
    at  [4, 46]
    at Script.runInContext (node:vm:140:12)
    at Script.runInNewContext (node:vm:145:17)
    at Object.runInNewContext (node:vm:299:38)
    at C (/Users/emily.klassen/.vscode/extensions/donjayamanne.typescript-notebook-2.0.6/out/extension/server/index.js:2:113345)
    at t.execCode (/Users/emily.klassen/.vscode/extensions/donjayamanne.typescript-notebook-2.0.6/out/extension/server/index.js:2:114312)

To solve this, the tsconfig should use the following to allow dynamic import expressions while still transforming import statements to require:

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node16"
  }
}