Cannot use import statement outside a module Error 해결하기
“Uncaught SyntaxError: Cannot use import statement outside a module” 오류를 해결해보자.
javascript ES6 에서 module을 import할 때 위와 같은 에러가 발생했다. 아무리 package.json 파일에 "type": "module" 태그를 추가해도 해결되지않아 몇시간을 고생했다. 이와 같은 경우 해결방법은 아래와 같다.
해결 방법
1. <script> type="module" 태그 추가
가장 최상단에서 실행되는 파일에 해당 에러가 발생하는 파일의 script 태그를 추가해준다. 아래의 예시를 보자. 디렉토리 구조는 다음과 같다.

프로그램 실행 시 메인이 되는 파일이 index.html 이고, import error가 발생하는 파일이 main.js 이라면, 메인 실행 파일(index.html)에 아래의 태그를 추가한다.
<script type="module" src="src/main.js">
import 모듈을 사용할 파일을 지정한다는 의미이다.
파일명 : index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="src/css/style.css" />
<title>Cat Search</title>
</head>
<body>
<div class='app'></div>
<script type="module" src="src/main.js"></script>
</body>
</html>
파일명 : main.js
import App from './App.js';
const app = new App(document.querySelector('.app'));
export는 아래와 같이 export default로 설정하면 된다. 참고로 .은 현재 디렉토리를 의미한다. 따라서, ./App.js는 현재 디렉토리에 위치에 있는 App.js 파일을 뜻한다.
파일명 : App.js
/*
import는 이해를 돕기위해 추가한 파일
*/
import SearchInput from "./components/SearchInput.js";
export default class App {
constructor($target) {
...
}
}
}
2. pacakge.json 파일에 “type” : “module” 추가
기본적으로 package.json 에 type 필드가 없으면 common.js(default) 방식이 적용되어 모듈 처리방식이 common.js 의 require 방식이된다. 따라서, ES6 의 import - export를 사용하려면 루트 디렉토리에 있는 package.json 파일에 "type": "module"를 추가해야한다.
파일명 : package.json
{
"name": "ilovecat",
"version": "1.0.0",
"type": "module", // 추가!
"description": "Programmers 2020 Dev-Matching",
"main": "index.js",
"scripts": {
"build": "babel src -d dist -w",
"lint": "eslint \"**/*.js\" --ignore-pattern node_modules/",
"test": "jest"
},
"repository": {
"type": "git",
"url": "git+https://github.com/woohyeonjo/ilovecat.git"
},
"author": "nnm",
"license": "MIT",
"bugs": {
"url": "https://github.com/woohyeonjo/ilovecat/issues"
},
"homepage": "https://github.com/woohyeonjo/ilovecat#readme",
"devDependencies": {
"@babel/cli": "^7.8.4",
"@babel/core": "^7.8.7",
"@babel/polyfill": "^7.8.7",
"@babel/preset-env": "^7.8.7",
"eslint": "^6.8.0",
"eslint-plugin-jest": "^23.11.0",
"jest": "^26.0.1"
}
}
3. 실행
이제 프로그램을 실행해보자. index.html -> main.js -> App.js 에서 SearchInput.js가 오류없이 정상적으로 생성(import)된다.

Leave a comment