Error when instantiating awarenessProtocol

When this line is ran:

const awareness = new awarenessProtocol.Awareness(new Y.Doc());

I get this error:

Error: Must use import to load ES Module: …/node_modules/y-protocols/awareness.js
require() of ES modules is not supported.
require() of …/node_modules/y-protocols/awareness.js from …/.next/server/pages/doc/[documentId].js is an ES module file as it is a .js file whose nearest parent package.json contains “type”: “module” which defines all .js files in that package scope as ES modules.
Instead rename awareness.js to end in .cjs, change the requiring code to use import(), or remove “type”: “module” from …/node_modules/y-protocols/package.json.

Project details:

"next": "10.0.3",
"react": "17.0.1",
"react-dom": "17.0.1",
"y-protocols": "1.0.1",
"y-webrtc": "10.1.7",
"y-websocket": "1.3.8",
"yjs": "13.4.7"

My Node version is v15.4.0
When I revert to Node v12.15.0 I get this error:

Cannot use import statement outside a module
module.exports = require(“lib0/encoding.js”);

I tried to throw together a quick codesandbox example, but it’s throwing a different error - I suspect they are related though:
https://codesandbox.io/s/elastic-payne-xhx60?file=/pages/index.js

Dynamically importing the module seems to be working.

(async () => {
      const awarenessProtocol = await import('y-protocols/awareness.js');
      const awareness = new awarenessProtocol.Awareness(ydoc);
})();

Exactly @Kolby,

y-protocols is an esm module. You need to import esm modules dynamically from commonjs modules.

Instead you can simply import the cjs module require('y-protocols/dist/awareness.cjs').

I set up my bundler to change the import paths when bundling. Cjs modules import from dist/[name].cjs. Mjs modules import the esm module directly.

Once node v10 deprecates we can use conditional imports to import the correct module automatically. Until then we have to do some manual work…

1 Like