IT story

예기치 않은 토큰 내보내기

hot-time 2020. 6. 13. 09:44
반응형

예기치 않은 토큰 내보내기


프로젝트에서 일부 ES6 코드를 실행하려고하는데 예기치 않은 토큰 내보내기 오류가 발생합니다.

export class MyClass {
  constructor() {
    console.log("es6");
  }
}

ES6 모듈 구문을 사용하고 있습니다.

이는 환경 (예 : node.js)이 ES6 모듈 구문을 지원해야 함을 의미합니다.

NodeJS는 module.exportsES6 모듈 구문 ( export키워드)이 아닌 CommonJS 모듈 구문 ( )을 사용합니다 .

해결책:

  • babelnpm 패키지를 사용 하여 ES6를 commonjs대상으로 변환

또는

  • CommonJS 구문으로 리팩터링하십시오.

이 오류가 발생하면 javascript 파일을 html 페이지에 포함시킨 방법과 관련이있을 수 있습니다. 모듈을로드 할 때 해당 파일을 명시 적으로 선언해야합니다. 예를 들면 다음과 같습니다.

//module.js:
function foo(){
   return "foo";
}

var bar = "bar";

export { foo, bar };

다음과 같이 스크립트를 포함시킬 때 :

<script src="module.js"></script>

오류가 발생합니다.

잡히지 않은 구문 오류 : 예기치 않은 토큰 내보내기

type 속성이 "module"로 설정된 파일을 포함해야합니다.

<script type="module" src="module.js"></script>

그런 다음 예상대로 작동하고 모듈을 다른 모듈로 가져올 준비가되었습니다.

import { foo, bar } from  "./module.js";

console.log( foo() );
console.log( bar );

ES6를 추가하려면 babel-preset-env

그리고 당신의 .babelrc:

{
  "presets": ["@babel/preset-env"]
}

babel 7을 적용하기 위해 @ghanbari 의견 덕분에 답변이 업데이트되었습니다.


바벨 패키지를 설치 @babel/core하고 @babel/preset직접 ES6 목표를 이해하지 못하는 노드 JS로 commonjs 대상에 ES6을하는 변환합니다.

npm install --save-dev @babel/core @babel/preset-env

그런 다음 .babelrc프로젝트의 루트 디렉토리에 이름 가진 하나의 구성 파일을 작성 하고 여기에이 코드를 추가해야합니다.

{ "presets": ["@babel/preset-env"] }


기본 JavaScript 모듈 내보내기를 간단히 사용할 수있을 때는 현재 Babel을 사용할 필요가 없습니다 (JS는 매우 강력 해졌습니다). 전체 튜토리얼 확인

Message.js

module.exports = 'Hello world';

app.js

var msg = require('./Messages.js');

console.log(msg); // Hello World

불행히도 ES6 구문을 사용하는 것은 노드에서 작동하지 않습니다. 불행히도 컴파일러가 내보내기 또는 가져 오기와 같은 구문을 이해하게하려면 명백히해야합니다.

npm install babel-cli --save

Now we need to create a .babelrc file, in the babelrc file, we’ll set babel to use the es2015 preset we installed as its preset when compiling to ES5.

At the root of our app, we’ll create a .babelrc file. $ npm install babel-preset-es2015 --save

At the root of our app, we’ll create a .babelrc file.

{  "presets": ["es2015"] }

Hope it works ... :)

참고URL : https://stackoverflow.com/questions/38296667/getting-unexpected-token-export

반응형