I'll try to chime in and provide some insight, though I don't consider myself to be an expert in Javascript module system and bundling.
Let's go from the start. Javascript originated from the browser world. Everything defined (variables, functions) was placed in a global scope (window) by the interpreter, after it was read. It was the browser's job to provide code to the JS interpreter, and it achieved this with the help of the <script>
tags.
Obviously, this is kind of low-tech and more sophistication is needed, so the CommonJS standard was created as a method of declaring JS modules and loading them (using require()
. A common implementation of the CommonJS standard is require.js, which uses define()
to descript how the modules are actually resolved.)
Next in history, the ES6 Javascript standard was created, which included a new type of JS modules, the "ES6 modules". These can be identified by the presence of import X from 'y'
statements.
This is where things go haywire, from my perspective. There's a ton of rules on how node decides to interpret a package or module as "ES module or CommonJS", see Modules: ECMAScript modules | Node.js v18.6.0 Documentation and Modules: CommonJS modules | Node.js v18.6.0 Documentation. Add, on top of this, the fact that our code gets through a lot of transformations: Volto uses Webpack to create "javascript bundles", which are mega-files of Javascript code, where a lot of our code gets concatenated in a single file (HTTP2 is relatively new, browsers restrict the number of parallel requests to a single domain, etc) and that code is also not the original, it is "transpiled", from the original "latest ES syntax" to something that older browsers can digest and support.
So, we're now getting to your error. It looks like dist/index.js of react-doc-viewer is targeting a "module-aware" system. In Volto (this is inherited from Razzle, as far as I am aware), we assume that everything under node_modules is already transpiled to CommonJS. Volto uses the Babel transpiler only for Volto code + Volto addons code, nothing more.
So the solution is to instruct Volto's Webpack + Babel bundling/transpilation machinery to also include the react-doc-viewer location when transpiling code. I wrote a blog post on something similar: Custom Volto configuration to fix Babel problems with react-leaflet · The Plone Expanse