Explain Codes LogoExplain Codes Logo

Getting Unexpected Token Export

javascript
module-export
javascript-versions
transpilation
Anton ShumikhinbyAnton Shumikhin·Dec 9, 2024
⚡TLDR

The Unexpected Token Export error likely means your code is using ES6 module syntax in an environment that does not support it. Switch to CommonJS syntax in such environments:

// ES6 export // export myFunction; // CommonJS // "I have traveled time for you" (Interstellar reference) module.exports.myFunction = myFunction;

In client-side, make sure to apply <script type="module">. In Node.js, rename your files to .mjs or include "type": "module" in your package.json:

{ "type": "module" }

Dealing with Node.js versions under v14.13.0

For Node.js versions older than v14.13.0, ES6 modules aren't supported. The good news is you’ve got options:

  • Refactor to use CommonJS syntax:
    const myFunction = require('./myFunction'); // Requires no introduction!
  • Use a transpiler like esbuild or Babel to opt-in to ES6:
    // "My transpile-ation will go on" (Titanic) require('esbuild').buildSync({ /* ...transpilation settings... */ });

TypeScript and ts-node: Your new BFFs

TypeScript provides smooth support for ES6 syntax in Node.js. Tools like ts-node or ts-node-dev allow running TypeScript files directly, "it's like running on the wind!" (Forrest Gump):

ts-node myScript.ts

Native support vs. Transpilation

While transpilation tools like esbuild and Babel are fantastic, using native ES6 module support in Node.js v14.13.0+ might just be the One Ring to rule them all (Lord of the Rings) if your environment supports it.

Module export-import dance

  • Export a class or function using export or export default in ES6:

    // "I am exported, hear me _node_" (Game of Thrones) export default class MyClass {}
  • Likewise, import these in another ES6 module:

    import MyClass from './myModule'; // "Keep your friends close, but your modules closer"
  • In CommonJS, exports go through the module.exports object:

    module.exports = { myGreatFunction, // "Hasta la vista, script" };
  • And import, you ask?

    const { myGreatFunction } = require('./myModule'); // "Say hello to my little function"

When imports and exports collide

Mixing ES6 and CommonJS syntax? A recipe for Import/Export error. Always double-check!

Browser Considerations

Make sure to specify type="module" in your script tags for browser code:

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

Scalable Module Strategies

To navigate a range of environments:

  • Use dynamic import() for conditional module loading.
  • Try lazy loading for a performance boost.
  • Utilize code splitting and chunking with webpack for efficient bundles.