Typescript ReferenceError: exports is not defined

Solution 1:

Few other Solutions for this issue

  • Add the following line before other references to Javascript. This is a nice little hack.
   <script>var exports = {};</script>

Solution 2:

EDIT:

This answer might not work depending if you're not targeting es5 anymore, I'll try to make the answer more complete.

Original Answer

If CommonJS isn't installed (which defines exports), you have to remove this line from your tsconfig.json:

 "module": "commonjs",

As per the comments, this alone may not work with later versions of tsc. If that is the case, you can install a module loader like CommonJS, SystemJS or RequireJS and then specify that.

Note:

Look at your main.js file that tsc generated. You will find this at the very top:

Object.defineProperty(exports, "__esModule", { value: true });

It is the root of the error message, and after removing "module": "commonjs",, it will vanish.

Solution 3:

A solution:

Remove "type": "module" from package.json.

Solution 4:

npm install @babel/plugin-transform-modules-commonjs

and add to to .babelrc plugins resolved my question.

Solution 5:

This is fixed by setting the module compiler option to es6:

{
  "compilerOptions": {     
    "module": "es6",
    "target": "es5",    
  }
}