javascriptecmascript-6module

How do I assign a function to the window object while using an ES6 module?


I am working with a third-party script, and I need to assign some functions to the window object, so that those functions are available to that third-party script (which will be running in the same browser window, called from the same domain). I must do this using ES6, using let and modules (import / export).

In ES5, I can do this:

//index.html
<script src="main.js"></script>
//third-party script will use window.myObj.blurt()
<script src="third-party-script.js"></script>
//main.js
var myObj = {};

myObj = {
  blurt: function(){
    console.log("Hello."); 
  }
}

blurt() is now available to be invoked off of the window object. I can put this in my browser console, and it will work: window.myObj.blurt().

I would like to do this, in ES6:

//index.html - note the type="module"
<script type="module" src="main.js"></script>
//third-party script will use window.myObj.blurt()
<script src="third-party-script.js"></script>
//main.js
import './my-window-functions.js';

//other existing code
//my-window-functions.js - NOT the third-party script - just my ES6 module system
let myObj = {};

myObj = {
  blurt: function(){
    console.log("Hello.");
  }
}

Now window.myObj.blurt() is undefined. How do I assign functions to the window object in this ecosystem?


Solution

  • In my-window-functions.js you need to export the myObj.

    let myObj = {};
    
        myObj = {
          blurt: function(){
            console.log("Hello.");
          }
        }
    export {myObj};
    

    Then in your main.js you need to import the myObj and assign it to the window object manually.

    import { myObj } from'./my-window-functions.js';
    
    window.myObj  = myObj;
    

    Then your 3rd party script can use the window.myObj.blurt().