matrix-org / matrix-js-sdk

Matrix Client-Server SDK for JavaScript
Apache License 2.0
1.49k stars 577 forks source link

matrix-js-sdk no longer works in node #4287

Open richvdh opened 4 days ago

richvdh commented 4 days ago

https://github.com/matrix-org/matrix-js-sdk/issues/4284 describes a problem wherein matrix-js-sdk no longer works in a CommonJS environment, but actually it's worse than that: it doesn't work in an ES modules environment either.

If we apply the fix from https://github.com/matrix-org/matrix-js-sdk/pull/4285, and run in an esm environment, I get:

node:internal/modules/esm/resolve:260
    throw new ERR_MODULE_NOT_FOUND(
          ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/rav/work/matrix-js-sdk/examples/node/node_modules/matrix-js-sdk/lib/matrix' imported from /home/rav/work/matrix-js-sdk/examples/node/node_modules/matrix-js-sdk/lib/index.js
    at finalizeResolution (node:internal/modules/esm/resolve:260:11)
    at moduleResolve (node:internal/modules/esm/resolve:920:10)
    at defaultResolve (node:internal/modules/esm/resolve:1119:11)
    at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:542:12)
    at ModuleLoader.resolve (node:internal/modules/esm/loader:511:25)
    at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:241:38)
    at ModuleJob._link (node:internal/modules/esm/module_job:126:49) {
  code: 'ERR_MODULE_NOT_FOUND',
  url: 'file:///home/rav/work/matrix-js-sdk/examples/node/node_modules/matrix-js-sdk/lib/matrix'
}

Node.js v22.2.0

The problem appears to be that index.js contains:

import * as matrixcs from "./matrix";

However, the file it actually wants is ./matrix.js, and the nodejs ESM resolver doesn't know it needs to add the extension. Likewise for every link in the project :/

richvdh commented 4 days ago

Apparently, the typescript way to do this is actually to

import {foo} from "./matrix.js"`; // note js extension

The .js is then retained in the output, but typescript is intelligent enough to use the ts file for type definitions (cf https://www.typescriptlang.org/docs/handbook/modules/reference.html#file-extension-substitution)