- typescript파일을 트랜스파일하지 않았다.
- typescript를 배우지도 않고 그저 공식문서에 있는것을 따라치고 실행해보았기 때문에 몰랐었다. 브라우저가 ts파일을 실행할 수 없다는 것을.
- 아래의 코드를 index.js로 변경해야한다.
- .ts파일을 컴파일해서 .js로 만들어야한다.
<script type="module" src="./index.ts"></script>
- 이번 경험으로 배운 것
- typescript는 브라우저에서 실행되지 않으니 컴파일해야한다.
- npx tsc 커맨드를 사용하면 컴파일할 수 있다.
- typescript에 namespace를 알 수 없다는 에러가 나올지라도 컴파일된 자바스크립트가
lib를 인식할 수 있다면 코드는 돌아간다. 예를 들자면 html에 정의한 bootstrap loader같은거 말이다.
- 사용한 예제코드
-
// Initialize and add the map let map; async function initMap(): Promise<void> { // The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary; const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary; // The map, centered at Uluru map = new Map( document.getElementById('map') as HTMLElement, { zoom: 4, center: position, mapId: 'DEMO_MAP_ID', } ); // The marker, positioned at Uluru const marker = new AdvancedMarkerElement({ map: map, position: position, title: 'Uluru' }); } initMap();
-
<html> <head> <title>Add Map</title> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <h3>My Google Maps Demo</h3> <!--The div element for the map --> <div id="map"></div> <!-- prettier-ignore --> <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))}) ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"});</script> </body> </html>
-
Reference
https://stackoverflow.com/questions/43555378/typescript-compiler-says-an-async-function-or-method-in-es5-es3-requires-the-p
https://developers.google.com/maps/documentation/javascript/adding-a-google-map?_gl=1*rt63i5*_up*MQ..*_ga*MTE1NDY2NDYzNC4xNzQzNzc5MDE5*_ga_NRWSTWS78N*MTc0Mzc3OTAxOC4xLjEuMTc0Mzc3OTAxOS4wLjAuMA..#typescript
chatGPT