Load and consume legacy JS modules (e.g. IIFEs) via ES6 module imports
Let's get this out of the way first, module features, if not explicitly exported, are privately scoped to the defining module. You can't get around this fact. But there are work-around options you may consider.
1. Assuming minimal modification of legacy code is acceptable
A work around with minimal changes to your legacy code would be to simply add Utils
and RandomHelper
to the window
object. For instance, change var Utils = (...)();
to window.Utils = (...)();
. Consequently, the object will be accessible from the global object by both legacy codes (loaded via import
) and newer code base.
2. Assuming absolutely no modification in the legacy code can be tolerated
A new ES6 module should be created as proxy for loading the legacy scripts:
// ./legacy-main.js
const utilsScript = await fetch( './Utils.js' )
const randomHelperScript = await fetch( './RandomHelper.js' )
const utilsScriptText = await utilsScript.text()
const randomHelperScriptText = await randomHelperScript.text()
// Support access to `Utils` via `import`
export const Utils = Function( `${utilsScriptText}; return Utils;` )()
// Additionally support access via global object
Object.defineProperty(window, 'Utils', { value: Utils })
// Support access to `RandomHelper` via `import`
// Note that `Utils` which is a dependency for `RandomHelper` ought to be explicitly injected
// into the scope of execution of `RandomHelper`.
export const RandomHelper = Function( 'Utils', `${randomHelperScriptText}; return RandomHelper;` )( Utils )
// Additionally support access via global object
Object.defineProperty(window, 'RandomHelper', { value: RandomHelper })
Finally, you may import Utils
and RandomHelper
from legacy-main.js
when required:
import { Utils, RandomHelper } from './legacy-main.js'
Utils.MyFunction()
RandomHelper.DoThing()