Skip to content

Conversation

@mkotelnikov
Copy link

Problem

In the current implementation the "requireFrom" method creates a new private cache object. It leads to loading of multiple versions of the same library.

Example

Example of method declarations in UMD files:

File: counter.js
-------------------
// UMD header goes here 
...
let counter = 0;
function incCounter() { return counter++; }
function decCounter() { return counter--; }
...
exports.incCounter = incCounter;
exports.decCounter = decCounter;
...

File: printCounter.js
--------------------------
// UMD header goes here 
...
const { incCounter } = require('counter');
function printCounter() {
   console.log('Counter:' + incCounter());
}
exports.printCounter = printCounter;
...

File: renderCounter.js
-----------------------------
// UMD header goes here 
...
const { incCounter } = require('counter');
function renderCounter() {
    const div = document.getElementById("counter-view")
    div.innerTexts = 'Counter: ' + incCounter();
}
exports.renderCounter = renderCounter;
...

Usage of these libraries:

const require = await import('https://cdn.jsdelivr.net/npm/d3-require@1/src/index.js')

const req1 = require.alias({
   'counter' : './js/counter.js',
   'printCounter' : './js/printCounter.js"
})
const { printCounter } = await req1('printCounter');
printCounter();
// => console : "Counter: 1"

...

const req2 = require.alias({
   'counter' : './js/counter.js',
   'renderCounter' : './js/renderCounter.js"
})

const { renderCounter } = await req2('renderCounter');
renderCounter();
// => div content is "Counter: 1" (Instead of "Counter: 2")

Problem: the same library "counter.js" was loaded twice even if it was resolved to the same final URL.

A real use case of this problem:
There is a main application and some modules are loaded separately to extend functionality of the main app. All of them use the same shared d3 require function to load UMD libraries. To resolve paths to a specific library the main application as well as extensions use the "require.alias". It leads to exceptions because each of them create a separate instance of the same module. (like react, react-dom etc)

Solution

Use the cache object as an additional parameter in the requireFrom method.

Set cache as a parameter of the requireFrom method to share loaded libraries between all require methods.

In the previous implementation the "alias" method creates a new "require" function with its own private cache object. This approach leads to creation of multiple copies of the same loaded libraries.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant