Search code examples
javascripthtmlecmascript-6sapui5ui5-tooling

import module and use it in another script scope in the same html


It can be as simple, but I couldn't find a way to solve it.

I am trying to import a module and use it in another script scope of html.

index.html

<script type="module">
   import defineCustomIcons from './webapp/utils/customFonts.js'
</script>
<script>
    sap.ui.getCore().attachInit(function () {
        sap.ui.require([
        ], function () {
            defineCustomIcons(jQuery);
            // some other code
        });
    });
</script>

customFonts.js

export default function defineCustomIcons(jQuery) {
  jQuery.sap.require('sap.ui.core.IconPool');
  sap.ui.core.IconPool.addIcon('sort_icon', 'customfont', 'icomoon', 'e900');
}

Unfortunately I can't use all js in one <script> as it fails to run then. Any ways this can be done?


Solution

  • This works:

    1. Save the function from the module to the window object,
    2. After window.onload, the function will be available globally.
    //file module.js
    export default function moduleApp () {
      console.log('this is moduleApp');
    }
    
    <script type="module">
      import moduleApp from './module.js';
      window.moduleApp = moduleApp;
    </script>
    <script>
      window.onload = () => {
        moduleApp();
      }
    </script>