Vue.js

Uncaught SyntaxError: Cannot use import statement outside a module

yisj 2022. 4. 29. 13:52

브라우저마다 에러가 다르게 뜬다.

  • 크롬에서: Uncaught SyntaxError: Cannot use import statement outside a module
  • 파이어폭스에서: SyntaxError: import declarations may only appear at top level of a module

이 에러는 script 태그에 type="module" 속성을 지정하면 해결된다.

 

왜 이런 에러가 발생하고 왜 type="module" 속성을 지정해야 할까? import문을 사용하기 때문이다. import문을 사용한다는 것은 곧 그 스크립트는 모듈울 사용한다는 것이다. script 태그에 type="module" 속성을 사용한다는 것은 곧 이 스크립트를 모듈로서 정의하겠다는 것과 같다.

type="module"을 지정하면 이 스크립트는 최상위 모듈이 되고, import문을 사용해서 다른 모듈을 불러서 사용할 수 있게 된다.