ReferenceError: exports is not defined


If you are getting the error for code that runs in the browser, try defining a global exports variable above the script tags that load your JS files.


<script>var exports = {};</script> 
<!-- 👇️ your JS script should be below --> 
<script src="index.js"></script>

This will define the exports variable and set it to an empty object, so you don't get an error if properties are accessed on it.

Browsers don't support the CommonJS syntax (unless using a tool like webpack) of require and module.exports, which is causing the error.

If you are running your code in the browser, try removing the module property from your tsconfig.json file and setting target to es6.


{ "compilerOptions": { "target": "es6", // 👈️ set this to es6 // "module": "commonjs", // 👈️ REMOVE this (if browser env) } }

When you remove the module option and set target to es6, your ES6 modules imports and exports won't get compiled to the older CommonJS syntax that browsers don't support.

Modern browsers support all ES6 features, so ES6 is a good choice.

If this doesn't work, try setting the type attribute to module in your script tags.


<!-- 👇️ correct path according to your setup --> <script type="module" src="index.js"></script>

And import and export using the ES6 Modules syntax.


import {v4} from 'uuid' export function sum(a, b) { return a + b; }

When you have set module to commonjs in your tsconfig.json, you are instructing TypeScript to emit CommonJS files and browsers don't support the CommonJS syntax, so this is a very likely cause of the error.


Saved you some valuable time?

Buy me a drink 🍺 to keep me motivated to create free content like this!