简体   繁体   中英

Babel Unexpected Token Export After Compile

I have created a project using ES6 syntax.

I am using Babel to compile the ES6 syntax JavaScript files to a version Node.js can run.

However, when I try to execute a file (index.js) that I believed to be compiled by babel, using node lib/index.js . I get the following error: SyntaxError: Unexpected token export .

I run the following command to compile my project: ./node_modules/.bin/babel src -d lib . src contains all of my files that are written in ES6.

It successfully compiles the directory with the message: Successfully compiled 15 files with Babel.

So, I am unsure as to why I am unable to run the compiled files. This is also my first time using babel so I may have missed something.

I have the following files which I believe are important to babel:

.babelrc

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

package.json - dev dependencies

"devDependencies": {
    "@babel/cli": "^7.8.4",
    "@babel/core": "^7.8.6",
    "@babel/polyfill": "^7.8.3",
    "@babel/preset-env": "^7.8.6",
    "@babel/register": "^7.8.6",
    "babel-loader": "^8.0.6"
}

Detailed error message:

/Users/c/Projects/Project1/src/credentials.js:10
export default Credentials;
^^^^^^

SyntaxError: Unexpected token export
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (/Users/c/Projects/Project1/lib/index.js:3:53)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)

It looks like in lib/index.js, it is referencing the ES6 file with the line:

var _credentials = _interopRequireDefault(require("../src/credentials")); .

In the local environment, you can just install these packages.

npm install @babel/core @babel/node --save-dev

And then in your package.json.

"scripts": {
    "start": "node --exec babel-node src/index.js"
  }

And .babelrc the same you have already. And it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM