javascript – Getting Unexpected Token Export

Javascript – Getting Unexpected Token Export

javascript – Getting Unexpected Token Export

You are utilizing ES6 Module syntax.

This means your atmosphere (e.g. node.js) should help ES6 Module syntax.

NodeJS makes use of CommonJS Module syntax (module.exports) not ES6 module syntax (export key phrase).

Solution:

  • Use babel npm package deal to transpile your ES6 to a commonjs goal

or

  • Refactor with CommonJS syntax.

Examples of CommonJS syntax are (from flaviocopes.com/commonjs/):

  • exports.uppercase = str => str.toUpperCase()
  • exports.a = 1

In case you get this error, it may also be associated to the way you included the JavaScript file into your html web page. When loading modules, it’s important to explicitly declare these recordsdata as such. Heres an instance:

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

var bar = bar;

export { foo, bar };

When you embrace the script like this:

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

You will get the error:

Uncaught SyntaxError: Unexpected token export

You want to incorporate the file with a sort attribute set to module:

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

then it ought to work as anticipated and you’re able to import your module in one other module:

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

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

javascript – Getting Unexpected Token Export

My two cents

Export

ES6

myClass.js

export class MyClass1 {
}
export class MyClass2 {
}

different.js

import { MyClass1, MyClass2 } from ./myClass;

CommonJS Alternative

myClass.js

class MyClass1 {
}
class MyClass2 {
}
module.exports = { MyClass1, MyClass2 }
// or
// exports = { MyClass1, MyClass2 };

different.js

const { MyClass1, MyClass2 } = require(./myClass);

Export Default

ES6

myClass.js

export default class MyClass {
}

different.js

import MyClass from ./myClass;

CommonJS Alternative

myClass.js

module.exports = class MyClass1 {
}

different.js

const MyClass = require(./myClass);

Hope this helps

READ :  How To Fix “TypeError: Object of type set is not JSON serializable” In Python

Related posts on java script :

Leave a Reply

Your email address will not be published. Required fields are marked *