[JS] Failed to load module script
➤ 표시 내용
자바스크립트에서 다른 파일을 import 할때 해당 파일의 경로가 잘못되었을 경우 흔히 나온다.
React.js의 경우 import 파일 경로를 ./ 와 .js를 생략할 수 있지만, 리액트를 사용하지 않은 경우, 확장자와 경로를 정확하게 해야한다.
➤ 해결법
파일의 경로와 확장자명을 잘 밝혀서 쓰면 된다. 상대 경로와 절대 경로에 대한 이해가 부족하다면 다른 블로그의 이 글 을 참고하자.
위의 오류와 비슷한 오류지만 다르게 해결해야하는 오류가 있는데, 저 방법으로 해결이 안된다면 확인하자. 이 글의 작성자는 위의 문제인 줄 알고 착각하다가 몇 시간을 날렸다!
처음에 소개한 오류는 MINE 타입이 text/html 이라 하였지만 위 오류는 text/plain이다. plain은 확장자가 아닌 텍스트 파일의 기본 상태라 이해하면 된다. 즉 서버 측에서 자바스크립트 파일을 일반적인 텍스트 파일로 인식 중이라는 것이다. 또 나같은 경우엔 모듈 파일(import할 파일)을 .module.js 파일이 아닌 .js 파일로 저장하였다. 사실 이 원인이 제일 큰 것 같다.
글 작성자는 서버에 대해 잘 몰라서 그냥 복붙으로 python을 이용해 배치파일에
python -m http.server 8080
으로만 쓰고 돌리고 있었는데, 이렇게 되면 서버에서 모듈 파일을 잘 인식하지 못한다. 다음 내용으로 파이썬 파일을 다시 생성해 로컬 서버를 다시 열어야한다.
import http.server
from http.server import HTTPServer, BaseHTTPRequestHandler
import socketserver
PORT = 8080
Handler = http.server.SimpleHTTPRequestHandler
Handler.extensions_map={
'.manifest': 'text/cache-manifest',
'.html': 'text/html',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.svg': 'image/svg+xml',
'.css': 'text/css',
'.js': 'text/javascript',
'.module.js': 'module',
'': 'application/octet-stream', # Default
}
httpd = socketserver.TCPServer(("", PORT), Handler)
print("serving at port", PORT)
httpd.serve_forever()
출처(내 4시간 헤맴의 결말이다) : Why would modules return a non-javascript MIME type of text/plain error when I am running the webpage the java is attached to through a python server? : learnjavascript (reddit.com)
Why would modules return a non-javascript MIME type of text/plain error when I am running the webpage the java is attached to th
This is the error I'm getting in google chrome Failed to load module script: The server responded with a non-JavaScript MIME type of...
www.reddit.com
방금 해결하고 소리지를 뻔 했다.
➤ 세줄요약
ㅡ MIME type of "text/html" 이라면 경로가 잘 못 된 것이다. 상대경로를 잘 확인하고 다시 해보자.
ㅡ MINE type of "text/plain" 이라면 import할 파일을 서버에서 일반 텍스트 파일로 인식하는 것이다. 모듈 파일의 확장자를 .module.js 로 하고 위에서 나온 코드처럼 서버에서 .module.js 파일을 module 파일로 인식할 수 있게 수정해주자.