6

In the Google Maps Javascript API example, I see they had something like this in the HTML:

<script type="module" src="./index.ts"></script>

and an empty export statement at the end of the TS/JS scripts.

let map;
function initMap() {
    map = new google.maps.Map(document.getElementById("map"), {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 8,
    });
}
window.initMap = initMap;
export {};

I don't see any examples or mentioning of empty exports on MDN, so I was wondering if anyone knew how it works. How does the script know to run it if the export is empty.

3
  • nothing magical about it. Apr 19, 2022 at 0:03
  • 3
    I suspect this might be a TypeScript thing, it doesn't look to do anything in JS Apr 19, 2022 at 0:09
  • 1
    The empty export is likely due to the usage of typescript, requiring all modules to have an import or export statement if --isolatedModules is set. As to how does it know to run, it is a module imported via a script tag, and so will be executed as such. A function is defined and assigned to the window. Apr 19, 2022 at 2:48

1 Answer 1

5

This looks like something in TypeScript; it has nothing to do with JavaScript.


If either of the cases below occurs, then you will need an import/export in the file.

  1. The TypeScript file is being called with the flag below.

    --isolatedModules
    
  2. The tsconfig.json file has the following key and value.

    {
      "isolatedModules": true
    }
    

According to typescriptlang.org, it states:

If isolatedModules is set, all implementation files must be modules (which means it has some form of import/export). An error occurs if any file isn’t a module.

If you try to run the TypeScript file with the --isolatedModules flag, you get an error like below.

'index.ts' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module.

As the error states above, the simplest way to fix the issue without adding any unnecessary import statements and/or export statements, it is easiest to export an empty object ({}), like so.

export {};

In summary, the empty object export will not do anything in JavaScript (or TypeScript, without the --isolatedModules flag). However, it comes in handy when running with the --isolatedModules flag.

The Google Maps JavaScript API example might be getting ready for this scenario, in case someone copied-and-pasted the code, so that they wouldn't get an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.