Jason
Jason

Reputation: 5787

Getting Unexpected Token Export

I am trying to run some ES6 code in my project but I am getting an unexpected token export error.

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

Upvotes: 573

Views: 1060951

Answers (20)

user22882067
user22882067

Reputation: 1

it is a simple common error sometimes... When we import into the plain Vanilla JS module a ./file instead of a ./file.js (especially when the import is generated by IntelliJ). It has happened to me several times, please consider this, too!

Upvotes: 0

Alb Rick Bi
Alb Rick Bi

Reputation: 33

Got through this problem: browsers only support the ES syntax and do not understand require and exports as used in CommonJS. The problem arises from importing files that have the .ts extension. To solve this use the ES6 module import in your files.

Example: Folder Structure

dist
src
|-app.ts
|-components
  |-button.ts
|-helper
  |-eventHander.ts
tsconfig.json
index.html
  1. In the tsconfig file, set "module": "ES2015"
  2. In the tsconfig file, set "outDir": "./dist"
  3. In the HTML file add the attribute <script type="module" src="./dist/app.js"></script>

You can read more about modules here: JavaScript modules

  • The eventHander.ts file
type Handler<T> = (e: T) => void;
const eventHander: Handler<Event> = (e: Event) => {
  e.preventDefault();
  alert("You Clicked");
};
export default eventHander;
  • In the button.ts
import eventHander from "../helper/eventHander.js"
function createButton(): HTMLElement {
  let button: HTMLElement;
  button = document.createElement("button");
  button.addEventListener("click", eventHander);
  button.innerText = "Click Me"
return button 
}
export default createButton 
  • In the app.ts file
import createButton from "./components/button.js";
const hostElement: HTMLElement = document.getElementById("app")!;
hostElement.insertAdjacentElement("beforeend", createButton());

Your HTML code should be like this:

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app"></div>
</body>
<script type="module" src="./dist/app.js"></script>

Upvotes: 1

Antonio Ooi
Antonio Ooi

Reputation: 1826

Another way to import ES6 module from CommonJS is to rename your ES6 module file to have .mjs extension. This is one way for backward compatibility. Then in your CommonJS code, you can import like this:

Top of file import:

import myClass from "./MyClass.mjs"

or Dynamic Import anywhere in the code:

const myClass = await import("./MyClass.mjs");

Note that your CommonJS file does not need to be renamed to .mjs. More info here.

Upvotes: 0

Thomas Andrews
Thomas Andrews

Reputation: 1597

I had modules working for a while, and then they weren't with this Uncaught SyntaxError: Unexpected token export error.

Turns out, I had added an open brace without a closed brace. Something like:

if (true) {
/* } missing here */

export function foo() {}

While the big error is the forgetting of the end }, the parser first finds an export inside the brace, which is a no-no.

The export keyword must be in the top level of the file.

So:

if (true) {
    export function foo() {}
}

would also be illegal. When the parser encounters this, it stops parsing right there, announcing the misuse of export vaguely, giving the same error it gives when it is loading a "non-module" JavaScript file that uses the export keyword. It never reports the underlying missing brace error.

Took me a long time to figure that out, so I'm posting here to help any future sufferers.

Ideally, the parser would report that export is only allowed at the top level of the file.

Upvotes: 2

Andrew Koster
Andrew Koster

Reputation: 1845

Just use tsx as your runtime instead of node. It will allow you to use normal import statements, without switching your project to type: module and without having to deal with the nasty consequences of type: module. In addition, you'll get TypeScript support.

Upvotes: 2

Barnstokkr
Barnstokkr

Reputation: 3129

My two cents

Export

ES6

myClass.js

export class MyClass1 {
}
export class MyClass2 {
}

other.js

import { MyClass1, MyClass2 } from './myClass';

CommonJS Alternative

myClass.js

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

other.js

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

Export Default

ES6

myClass.js

export default class MyClass {
}

other.js

import MyClass from './myClass';

CommonJS Alternative

myClass.js

module.exports = class MyClass1 {
}

other.js

const MyClass = require('./myClass');

Upvotes: 153

Amine Nafkha
Amine Nafkha

Reputation: 19

// ✅ Using module.exports instead of export module.exports = { Person, };

Upvotes: -4

Razib Hossain
Razib Hossain

Reputation: 756

Normally import not working in a .js extension because by default js means cjs version of javascript. If you want to es6 feature you need to rename the .js extension to the .mjs extension

parent.mjs

export default class Car {
   constructor(brand) {
   this.carname = brand;
}
 present() {
   return 'I have a ' + this.carname;
  }
}

child.mjs

import Car from './parent.mjs'
export default class Model extends Car {
constructor(brand, mod , country) {
  super(brand);
  this.model = mod;
  this.country = country;
}
show() {
  return this.present() + ', it is a ' + this.model + "i am from " + 
  this.country;
  }
}

index.html

<!DOCTYPE html>
 <html lang="en" class="no-js">
  <head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, 
shrink-to-fit=no">
  <title>Quick Start Pack Template</title>
 </head>
 <div class="demo"></div>
 <script type="module">
   import Model from './child.mjs'
   let value = new Model("Ford", "Mustang", "bangladesh")
   document.querySelector(".demo").innerHTML = value.show()
 </script>
 </body>
 </html>

Finally run this code on live server

Upvotes: 0

Sebastian
Sebastian

Reputation: 442

For those that are viewing this in 2022, I had the same error, however I changed my code to something like this:

    module.exports = () => {
    getUsers: () => users;
    addUser: (user) => users.push(user);
  };

Upvotes: 0

bcr666
bcr666

Reputation: 2197

I experienced this problem and it took me an hour to find my problem.

The problem was that I was changing my code from non-modules to modules and I forgot to delete the imported script file.

My "table.js" file had the following line. This is the module file.

export function tableize(tableIdentifier) {

My "orderinquiry.js" file had the following line.

import { tableize, changeColumnSizesDynamic } from '../common/table.js';

My "orderinquiry.html" had the following two lines.

<script src='/resources/js/common/table.js'></script>
<script type='module' src='/resources/js/client/orderinquiry.js'></script>

While the second line is good and declares type='module. But the first line directly links to table.js and caused the unexpected error. Everything started working when I removed that first <script>.

Upvotes: 0

Phil Ricketts
Phil Ricketts

Reputation: 8710

Updated for 2022

You are using EcmaScript Module (ESM or 'ES6 Modules') syntax but your environment does not support it.

NodeJS versions prior to v14.13.0 do not support ESM (export keyword syntax) and use CommonJS Modules (module.exports property syntax). NodeJS v14.13.0 and newer supports ESM but it must be enabled first.

Solutions:

  • If you are using NodeJS v14.13.0 or newer (which does support ESM) you can enable it by setting "type":"module" in your project package.json
  • Refactor with CommonJS Module syntax (for older versions of NodeJS)
  • Consider using TypeScript alongside ts-node or ts-node-dev npm packages (for instant transpilation at development time) and write TypeScript in .ts files
  • Transpile ESM to CommonJS using esbuild (esbuild package on npm) configured to transpile your ES6 javascript to a CommonJS target supported by your environment. (babel is no longer recommended)

Upvotes: 556

C B
C B

Reputation: 13344

In the latest versions of Nodejs (v17?) you can use top-level "import", "async", "await" by using the .mjs file extension - instead of transpiling or workarounds.

   // > node my.mjs
   
   import {MyClass} from 'https://someurl'
   async func () {
     // return some promise
   }
   await func ()

Upvotes: -1

YouBee
YouBee

Reputation: 2071

Install the babel packages @babel/core and @babel/preset which will convert ES6 to a commonjs target as node js doesn't understand ES6 targets directly

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

Then you need to create one configuration file with name .babelrc in your project's root directory and add this code there.

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

Upvotes: 8

badasscoder
badasscoder

Reputation: 21

I actually want to add simple solution. use constand backticks(`).

const model = `<script type="module" src="/"></<script>`

Upvotes: -5

Paramsmit Sanghani
Paramsmit Sanghani

Reputation: 15

I got the unexpected token export error also when I was trying to import a local javascript module in my project. I solved it by declaring a type as a module when adding a script tag in my index.html file.

<script src = "./path/to/the/module/" type = "module"></script>

Upvotes: -1

Wilt
Wilt

Reputation: 44413

In case you get this error, it might also be related to how you included the JavaScript file into your html page. When loading modules, you have to explicitly declare those files as such. Here's an example:

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

var bar = "bar";

export { foo, bar };

When you include the script like this:

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

You will get the error:

Uncaught SyntaxError: Unexpected token export

You need to include the file with a type attribute set to "module":

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

then it should work as expected and you are ready to import your module in another module:

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

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

Upvotes: 425

Alex Cory
Alex Cory

Reputation: 11865

I fixed this by making an entry point file like.

// index.js
require = require('esm')(module)
module.exports = require('./app.js')

and any file I imported inside app.js and beyond worked with imports/exports now you just run it like node index.js

Note: if app.js uses export default, this becomes require('./app.js').default when using the entry point file.

Upvotes: 25

Alvin Konda
Alvin Konda

Reputation: 3248

There is no need to use Babel at this moment (JS has become very powerful) when you can simply use the default JavaScript module exports. Check full tutorial

Message.js

module.exports = 'Hello world';

app.js

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

console.log(msg); // Hello World

Upvotes: 25

Jalal
Jalal

Reputation: 3644

To use ES6 add babel-preset-env

and in your .babelrc:

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

Answer updated thanks to @ghanbari comment to apply babel 7.

Upvotes: 13

purushottam banerjee
purushottam banerjee

Reputation: 57

Using ES6 syntax does not work in node, unfortunately, you have to have babel apparently to make the compiler understand syntax such as export or import.

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 ... :)

Upvotes: -2

Related Questions