Solutions:
First Basic Solution:
Warning: THE APPROACH BELOW FOR MODULES CAN'T WORK! Some modules are plain scripts, some else are cjs, other umd... Its doesn't have a compatibility for taken this way.
"set all in relative path after make static the modules"
yourexpress.use( '/node_modules/', express.static( yourbaseroot+'/node_modules/') )
import React from '../node_modules/react/index.js'
import { hydrateRoot } from '../node_modules/react-dom/index.js'
import { renderToString } from '../node_modules/react-dom/server.js'
import { html } from '../node_modules/htm/react/index.js'
Second (and better) Approach:
One (or the only) of better solution it's make a cross load function. In my case i make an importer async make a first good solution.
// importer:
async function importModule(modulePath) {
if(typeof window === 'undefined'){
return require(modulePath)
} else {
const module = await import(modulePath)
return module.default || module
}
}
//usage:
const MyReactComponent = async (props) => {
var React, MyLib
if(typeof window === 'undefined'){
React = await importModule('react')
MyLib = await importModule('MyLib')
} else {
React = window.React
MyLib = window.MyLib
}
// do...
}
in any case, however, you need to use the horrible solution of export into window global object part of your app (like a builder, ex webpack)
Other notes, approach and deliriums
After different try I understand that right way is respect imports/exports types and not load the libs direct via nodejs modules paths in search of an unpraticable absolutism. However, commonJS and ES6 are an unconciliable enemies if you have its into the same page and you think to share something. One lock the others and vice versa in recursive loop.
So, it's a good idea to understand (obviously) the file structure of what we want to do, set up node for commonJS and get/share to parallelize your libraries both on the server and the web window object.
function myLibOrComponent () { ... }
typeof window === 'undefined' ?
module.exports = myLibOrComponent : // node export
window.myLibOrComponent = myLibOrComponent // web export
so, get it in same way... exemple:
const myLibOrComponent = typeof window === 'undefined' ?
require('myLibOrComponent ') : // node import
window.myLibOrComponent // web global object
another way for components is:
import('./myLibOrComponent.js').then( () => { do... })
const myLibOrComponent = React.lazy(() => import('./myLibOrComponent'))
Exporting in window or self (like webpack) global object it's not a good practice but, unfortunately, I don't find any other way to reconcile the two type of script, formatted for two (or more) type of importing type.