'Error Typescript - Uncaught ReferenceError: exports is not defined

I am facing this issue. I created this simple app.ts to learn about promises in Typescript:

import {Promise} from 'es6-promise'

(() => {
console.log('inicio');

const prom1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('Se termino el timeout');
    }, 1000);
});

prom1
    .then(mensaje => console.log(mensaje))
    .catch(err => console.warn(err))

console.log('fin');
})();

Then I compile this (tsc app.ts). And it had create an app.js:

"use strict";
exports.__esModule = true;
var es6_promise_1 = require("es6-promise");
(function () {
    console.log('inicio');
    var prom1 = new es6_promise_1.Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve('Se termino el timeout');
        }, 1000);
    });
    prom1
        .then(function (mensaje) { return console.log(mensaje); })["catch"](function (err) { return console.warn(err); });
    console.log('fin');
})();

Also, this is the tsconfig.json

{
  "exclude": ["typescript"],
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "noImplicitAny": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

but when I run this in the browser console, it appears the following alert:

Uncaught ReferenceError: exports is not defined
    at app.js:2

I am frustrated and have tried everything that has appeared on the internet and nothing works. I am trying to learn how to use Angular



Solution 1:[1]

but when I run this in the console

If you mean the browser console, that's as expected. That code isn't compiled for use standalone in a browser, it's compiled to be used by something that understands CommonJS modules. (Browsers don't, without library/bundler support.)

If you just want to compile TypeScript to JavaScript and run the result in a browser directly, tell TypeScript to output ESM (via the module option, setting it to "ESNext").

But for an Angular project, you probably want to use a bundler like Webpack or Rollup instead.

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 T.J. Crowder