'SyntaxError: Unexpected token 'export' Underscore.js

I'm getting this error when I copy-paste the underscore.js to my console. Error screenshot "Uncaught SyntaxError; Unexpected token 'export'"

I tried on both Chrome Version 100.0.4896.127 and Opera LVL3 (core: 85.0.4341.72) if that helps.



Solution 1:[1]

Unexpected token 'export' means that the engine encountered JavaScript's export keyword, which is only allowed when you do <script type=module>. This means that you probably copied the ESM bundle to your console (underscore-esm.js), which is meant for this scenario.

For copy-pasting into the console, the UMD bundle (underscore-umd.js) is more suitable. This will give you a global _ variable that lets you access all Underscore functions.

When writing JavaScript projects "for serious", you will generally either do something like this:

import _, { times, debounce } from 'underscore';

if you are using an ESM platform (which may require setting up an import map or similar alias configuration in some cases), or something like this:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/underscore-umd-min.js"></script>

if you are attaching your dependencies directly to an HTML page.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Julian