로컬에서 ES6모듈 사용시 에러가 나는 경우

LeeWonjin·2022년 4월 2일
0

문제해결

목록 보기
5/21

배경

index.html이 존재하고, 이 문서에서는 script.js를 불러온다.
script.js에서는 모듈 anotherScript.js를 불러온다.

<!-- index.html -->
<body>
  <뭐시기></뭐시기>
  <뭐시기2></뭐시기2>
  
  <script src="./script.js"></script>
</body>
// script.js
import anotherScript from "./anotherScript.js";
console.log('something');

type어트리뷰트

index.html을 웹브라우저에 실행하면 아래와 같은 오류를 볼 수 있다.

Uncaught SyntaxError: Cannot use import statement outside a module (at firevoid.js:2:1)

이는 script태그의 문제로, 아래와 같이 type="module" 어트리뷰트를 추가해주면 된다.

기존 : <script src="./firevoid.js"></script>
변경 : <script type="module" src="./firevoid.js"></script>

CORS

type 어트리뷰트를 추가했다면, 아래와 같은 CORS에러를 만나게 된다.
부르는 곳과, 불리는 곳이 어느정도 같아야만 CORS를 만족시켜 해당 에러를 없앨 수 있다.
그러나, 로컬에서는 같고 다르고 문제에 앞서 애초에 그 값이 null이다. 그래서 CORS에러 해결이 안된다.

  1. Access to script at 'file:///C:/Users/goran/Desktop/firevoid/firevoid.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https. firevoid.html:48 GET
  2. file:///C:/Users/goran/Desktop/firevoid/firevoid.js net::ERR_FAILED

따라서, npm 패키지 중 http-server를 사용한다.

npx http-server

실행하면 아래와 같은 내용이 나오며 실행된다. Available on 아래의 주소 중 하나로 들어가면, CORS문제가 해결된 것을 확인할 수 있다.

Starting up http-server, serving ./

http-server version: 14.1.0    

http-server settings: 
CORS: disabled
Cache: 3600 seconds
Connection Timeout: 120 seconds
Directory Listings: visible
AutoIndex: visible
Serve GZIP Files: false
Serve Brotli Files: false
Default File Extension: none

Available on:
  http://192.168.0.15:8080
  http://127.0.0.1:8080
Hit CTRL-C to stop the server

부록 : npx가 없을 때 해결방법

node 깔면 된다.
https://nodejs.org/ko/

profile
노는게 제일 좋습니다.

0개의 댓글