JS) Cannot use import statement outside a module

pulpo_0402·2023년 9월 4일
0

상황

동작을 총괄하는 main.js에서 다른 js 파일에 작성한 기능(=개별 모듈)들을 불러오고자 했으나, main.js에서 Cannot use import statement outside a module 에러가 났다.


해결방법

최상단 html 파일에서 오류가 난 js 파일을 불러오는 script 태그에 type="module"을 추가한다.

  • index.html (최상단 html)
    main.js가 모듈이 아니라는 에러가 났으므로 main.js를 불러오는 스크립트 태그의 typemodule로 지정해준다.
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8"/>
	...
    <script src="./scripts/main.js" type="module" defer></script>
  </head>
  ...

  • wisesaying.js에서 함수 내보내기
    export를 사용해 내보낸다.
const createWordsEl = () => {
    alert("in");
}

export {createWordsEl};

  • main.js에서 받아오기
    importexport한 요소의 이름과 경로를 지정해 받아온다.
import { createWordsEl } from "./wisesaying.js";

const clickSayingWordsLabel = () => {
    createWordsEl(); 
  	// 오류 없이 작동: in을 출력하는 alert 실행
}

0개의 댓글