참고 − 이 예제를 실행하려면 localhost 서버가 필요합니다. −
다음은 JavaScript에서 동적 가져오기를 위한 코드입니다 -
예시
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 18px; font-weight: 500; color: rebeccapurple; } </style> </head> <body> <h1>Awaiting on dynamic imports in JavaScript</h1> <div class="result"></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to dynamically import modules</h3> <script> document.querySelector(".Btn").addEventListener("click", loadModule); let resEle = document.querySelector(".result"); async function loadModule() { let test = await import("./sample.js"); resEle.innerHTML += test.testImport() + "<br>"; resEle.innerHTML += test.tellTime(); } </script> </body> </html>
샘플.js
function testImport() { return "Module testImport has been imported" + "<br>"; } function tellTime() { return new Date(); } export { testImport, tellTime };
출력
'여기를 클릭' 버튼을 클릭하면 -