간단하게 테스트 해보고 싶어서 index.html 파일과 index.js 파일을 만들고, 파일 경로로 index.html을 열었다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
안녕
<script src="./index.js"></script>
</body>
</html>
import { HI } from './index2.js';
console.log(HI)
근데 아래와 같은 에러가 발생했다.
Uncaught SyntaxError: Cannot use import statement outside a module

script 태그에 module="type" 을 넣어주면 해결된다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
안녕
<script src="./index.js" type="module"></script> // 여기
</body>
</html>
근데 또 아래와 같은 에러가 발생했다.
from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.

검색해 보니 서버로 html을 열면 해결된다.
VSCode 에 Live Server 플러그인을 설치 후 Live Server에 올려주거나, 아파치 서버 켜서 거기서 실행시켜주면 된다.
그렇다면 왜 CORS 에러가 발생하는가?
MDN에 따르면 type을 module로 설정한 <script> 태그가 포함된 HTML 파일을 로컬에서 불러올 경우 javascript 모듈 보안 요구사항으로 인해 CORS 오류가 발생한다고 한다.
'JavaScript' 카테고리의 다른 글
| JavaScript 네이밍 규칙 (0) | 2023.03.08 |
|---|---|
| 변수 네이밍 기술 (0) | 2023.03.08 |
| ios safari에서 스크롤 하단에 있는 버튼(링크) 안 눌리는 이슈 (0) | 2022.07.19 |
| vercel에서 gsap build 이슈 (0) | 2022.07.19 |
| Bearer와 jwt (0) | 2022.02.08 |