415

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");
  }
}
str
  • 38,402
  • 15
  • 99
  • 123
Jason
  • 4,207
  • 2
  • 8
  • 3
  • 6
    there is not enough information about your environment or configuration to offer any assistance. This error is suggesting that either webpack or babel are not working correctly, as `export` is only available in ES6, and those modules are what provide ES6 support. – Claies Jul 10 '16 at 21:44
  • 52
    You should use `module.exports = MyClass`, not `export class MyClass` – onmyway133 Aug 04 '17 at 09:47
  • If you're running this in Node > 12, rename the file to myFile.mjs. That `mjs` extension should tell Node you're using ES6 Module syntax. – Yair Kukielka Oct 27 '21 at 07:23

11 Answers11

422

Updated for 2022

You are using ES6 Module syntax.

This means your environment (e.g. node v14.13.0 or newer) must support ESM (Ecmascript Module Syntax).

NodeJS since v14.13.0 supports EcmaScript Module Syntax but it must be enabled by adding the property "type":"module" to package.json. NodeJS versions prior to v14.13.0 uses CommonJS Module syntax by default (module.exports), not ES6 module syntax (export keyword).

Solutions:

  • Enable module support in package.json as outlined above, if
  • Refactor with CommonJS syntax (for older versions of NodeJS)
  • Accept that TypeScript is just better and write .ts files along with ts-node or ts-node-dev npm package
  • (deprecated) Use babel npm package to transpile your ES6 to a commonjs target

Javascript Module standards have changed a lot in recent years, so it can be a bit confusing.

Phil Ricketts
  • 7,106
  • 3
  • 27
  • 31
  • 41
    When will nodejs support `import` natively? I thought v10.0.0 would have it but apparently not. – chovy Apr 30 '18 at 20:42
  • 8
    @chovy experimental support is available with flag "--experimental-modules". Files needs to have a .mjs extension – Giovanni P. May 06 '18 at 22:44
  • 3
    I'm getting this error using Chrome 66 with native support for modules. – Tom Russell Feb 23 '19 at 06:14
  • BTW: note that while node10/node12 support modules behind the flag, [they don't support it in REPL mode -- however it is supported in eval mode in node12](https://stackoverflow.com/q/54784608/245966). – jakub.g Jul 17 '19 at 13:27
  • > Add "type": "module" to the package.json for your project, and Node.js will treat all .js files in your project as ES modules. - https://medium.com/@nodejs/announcing-a-new-experimental-modules-1be8d2d6c2ff – Brian Burns Aug 01 '19 at 01:55
  • 3
    For someone are still not clear about CommonJs Syntax. please checkout this link, may help a little bit. https://flaviocopes.com/commonjs/ – L.T. Aug 26 '19 at 13:19
  • 18
    Not really a helpful comment, but for someone outside of the front-end world it is all quite confusing. Just wanted to build a module used for web, which I am testing in the CLI. I would've assumed that Node.js being mature environment would support ES6 syntax out of the box. – NeverEndingQueue Apr 04 '20 at 19:53
  • 1
    It's been quite a while, and this answer was true at the time, but many Node versions later is now more misleading than helpful. ESM supported landed several versions before the current LTS version (feature flagged in v12, landed in v14, current LTS is v16). As long as you have `"type": "module"` in your `package.json`, ESM syntax will work fine. It would be a good idea to explicitly state which obsolete version(s) of Node this answer was for, and how it's no longer applicable to current Node. – Mike 'Pomax' Kamermans Jan 28 '22 at 18:07
  • 1
    @Mike'Pomax'Kamermans Just seen your comment, I've updated the answer accordingly. Things move quickly in Javascript land! – Phil Ricketts Mar 15 '22 at 20:39
  • Sometimes they do - ESM took _forever_ to go from draft to landed (and Node still hasn't commited to a true switchover unfortunately). As for transpiling, [esbuild](https://esbuild.github.io) is probably a better suggestion, given how many orders of magnitude faster it is. – Mike 'Pomax' Kamermans Mar 15 '22 at 22:03
299

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 );
Pang
  • 9,073
  • 146
  • 84
  • 117
Wilt
  • 37,062
  • 11
  • 138
  • 192
  • 81
    unlike the "most-upvoted" answer, this actually solves the problem and explains why it is happening without suggesting that the only option is to leverage a CommonJS method, APM method, or to transpile our code... This would also be an exception to the w3c standard where `type` is expected to be a valid mime type (aka. media type), so this was an unexpected find. Thanks! – Shaun Wilson May 20 '18 at 00:51
  • 4
    This fixes the error but I then get "Unexpected token {" on the line of the import statement in Chrome 67 with script that is inline eg – PandaWood Jul 27 '18 at 12:01
  • 1
    @PandaWood You have to use ``, when you import from module. I tested it in recent version of Chromium. – Vladimir S. Aug 01 '18 at 07:10
  • I just want to mention when using expert default you are not intended to put the same name, on the other hand export only you must follow same name for function, object ..etc In addition to that, you should import with .js as suffix – Husien Aug 24 '21 at 18:12
  • How do you use the `import ...` when loading a script from an external site such as jsDelivr? – pir Sep 29 '21 at 00:13
  • The most upvoted answer didn't solve my problem, this one did. – Joris Limonier Dec 30 '21 at 11:39
104

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');

Hope this helps

Barnstokkr
  • 2,594
  • 1
  • 18
  • 34
  • 1
    Thanks! This really helped me understand the difference between ES6 and CommonJS import/export patterns. – camslice Nov 15 '21 at 03:37
22

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.

mattdlockyer
  • 6,546
  • 4
  • 36
  • 44
Alex Cory
  • 8,820
  • 7
  • 47
  • 60
17

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
Alvin Konda
  • 2,314
  • 19
  • 22
12

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.

Jalal
  • 2,757
  • 2
  • 32
  • 41
  • 7
    @monsto this question was already tagged `babel` by the author. Whilst Phil Ricketts answer does clarify the problem, which is good, this answer is a direct solution to the author's problem. – boycy Apr 24 '18 at 15:00
  • "@babel/preset-env" – ghanbari Jun 16 '19 at 10:15
6

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"] }

YouBee
  • 1,727
  • 13
  • 16
  • 1
    I also needed to install @babel/register, otherwise I would still get "SyntaxError: Cannot use import statement outside a module" – molecular Nov 29 '19 at 09:05
  • i'm grateful that someone actually mentioned how you could make it compatible with es6 in this q&a thread! jeez. – Hari Reddy Aug 14 '21 at 22:50
0

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>

-1

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

-1

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 ()
John Williams
  • 10,960
  • 4
  • 35
  • 47
-5

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

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