A New Chapter for MagicMirror: The Community Takes the Lead
Read the statement by Michael Teeuw here.
Read the statement by Michael Teeuw here.
Best practice for `import` ESM in MM module?
-
Hey guys,
I have a small question about development.When you have to import
ESM
into your module, how you can do that?This is my way.
start: function() { this._domCreated = null this._modules = {} let _imports = [] let _domReady = new Promise((resolve, reject) => { this._domCreated = resolve }) _imports.push(new Promise((resolve, reject) => { import('/' + this.file('something.mjs')).then(({ moduleA }) => { this._modules.moduleA = moduleA }) })) Promise.allSettled([..._imports, _domReady]).then((result) => { console.log('All ESM modules and DOM are readied. Now I can do anything...') this._modules.moduleA.doSomeInitializing() }) } notificationReceived: function(notification, payload, sender) { if (notification === 'DOM_OBJECTS_CREATED') { this._domCreated() } }
But I’m not sure this is the best way. Is there any different approach?
-
@mmrize u cannot read files directly in browser.
u can load them via web server, but I don’t know how u ‘import’ them. u would have to inject script like
<script src=
tag
looks like adding type=module
https://www.sitepoint.com/using-es-modules/or getScripts in mm module name.js
but still loaded from server url
-
- Modern browsers can directly
import
ESM through JS regardless it exists locally or externally. . (Anyway, the above code works really.) - Loading ESM via
<script type="module">
tag will probably be the one way but It will have a global namespace scope. I’m afraid of the risks of collision among MM modules that might be using the same namespace. getScripts()
doesn’t supportscript type
. So some codes for injecting proper script tag is needed by the developer himself,- To load ESM with MM-module-level scoping, using
import()
and binding the namespace to the MM module would be possible. however, there will be some pitfalls,import()
is an asynchronous function. To prevent referencing unloaded ES modules or to avoid handling of DOM by ES Modules before DOM is created, so some tricks might be needed to confirm everything is ready. (Above my code is that.). - So I’m just seeking another or better way if exists.
- Modern browsers can directly
-