'Unexpected Token Export' error
Older Article
This article was published 8 years ago. Some information may be outdated or no longer applicable.
You try to use ES2015 export/import statements in Node.js and get slapped with “Unexpected Token Export”. There’s a reason this happens. Let’s look at why.
Module syntax
JavaScript has multiple module syntaxes: CommonJS, ES6/ES2015 modules, AMD (Asynchronous Module Definition), and a few others.
So you’ve just picked up ES2015. You’ve learnt about the module system with its shiny export/import statements. You create a class (because hey, that’s another thing you just learnt) and try to export it for reuse in your main application file:
// hero.class.js
export class Hero {
constructor(name) {
this.name = name;
}
}
// app.js
import { Hero } from './hero.class';
const superman = new Hero('Superman');
Run it. Boom: ‘unexpected token “export”’.
The reason’s simple. Node.js uses CommonJS module syntax, which expects two different keywords: require() and module.exports.
You’ve got two options. First, rewrite the code to use CommonJS:
// hero.class.js
class Hero {
constructor(name) {
this.name = name;
}
}
module.exports = Hero;
// app.js
const Hero = require('./hero.class');
const superman = new Hero('Superman');
But if you’ve got a large codebase, rewriting everything might not be practical.
Transpile using Babel
The other option: transpile the export/import syntax using Babel.
Install the appropriate Babel plugin: npm i --save-dev transform-es2015-modules-commonjs.
Then transpile your files (assuming Babel’s installed globally): babel --plugin transform-es2015-modules-commonjs *.js -d build.
You could also specify this plugin in a
.babelrcconfig file instead.
Running that command creates a build folder with two JavaScript files containing:
// hero.class.js
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
class Hero {
constructor(name) {
this.name = name;
}
}
exports.Hero = Hero;
// app.js
('use strict');
var _class = require('./hero.class');
const superman = new _class.Hero('Superman');
Babel’s automatically converted the code to CommonJS-style modules.