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.
CodePudding user response:
This looks like something in TypeScript; it has nothing to do with JavaScript.
If either of the cases occur, then you will need an import/export in the file.
The TypeScript file is being called with the flag below.
--isolatedModulesThe
tsconfig.jsonfile has the following key.{ "isolatedModules" }
According to typescriptlang.com, it states:
If
isolatedModulesis set, all implementation files must be modules (which means it has some form ofimport/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.
❌ '
input.tsx' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add animport,export, or an empty 'export {}' statement to make it a module.
As the error states above, the simplist 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.
