JavaScript is a great programming language. There is so much you can do with it, there are many different flavors and variants, and it is flexible. One downside to this flexibility, particularly in the context of being able to use it in different environments with different ways to handle dependencies, is making sure you use the proper syntax and keywords. If you have issues here then you might run into the Unexpected token 'export'
error.
The situations that can cause the error boil down to attempting to use export
which is ES6 module syntax without the project being properly set up for it. This can happen in JavaScript or TypeScript projects within a <script>
tag or one using a package.json
. Let’s say you have a file with a few helpful functions in it called helpers.js
:
// helpers.js
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
Code language: JavaScript (javascript)
If you wanted to use these extremely useful functions in an html file you may try this:
<!-- index.html -->
<!DOCTYPE html>
<html>
<div>
<h1>hello world!</h1>
</div>
</html>
<script src="./helpers.js"></script>
Code language: HTML, XML (xml)
Similarly, if these functions were within a Node project, you may try to run the following:
// ...helpers.js
console.log(add(1, 2));
Code language: JavaScript (javascript)
Doing either of these things will net you the Unexpected token 'export'
error. Let’s figure this out.
Fortunately the solution here is quite simple. If you want to use export
, you will need to specify that these files should use ES6 Module syntax. For <script>
tags, this is done like so:
<script src="./helpers.js" type="module"></script>
Code language: HTML, XML (xml)
In a Node project, you would add the same type value to your package.json
:
// package.json
{
// ...
"type": "module"
}
Code language: JSON / JSON with Comments (json)
If you would like to avoid changing the module syntax in your project then you will need to refactor the file using export
to conform to CommonJS syntax rather than ES6. Using the same example as above, that would be done like so:
// helpers.js
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
module.exports = {
add,
multiply,
};
// to use in another file:
const helpers = require("./helpers.js");
console.log(helpers.add(1, 2)); // no error
Code language: JavaScript (javascript)
Working with ES6 modules can be tricky so there are a couple different errors that can pop up while working with them. We’ve covered a similar error on this blog before, so feel free to check out that post here. Otherwise, thanks for reading and happy coding.