Why does my compiler causes an error due compiling my .ts file into .js?

175 Views Asked by At

I have 2 .ts files:

linked_list.ts

class Node {
  *****
}
class LinkedList{
  *****
}
export {LinkedList};

and index.ts:

import {LinkedList} from "./linked_list";
class LinkedListStack{
  *****
}

My compiler compiles them into:

linked_list.js:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LinkedList = void 0;

var Node = /** @class */ (function () {
    function Node(value) {
        *****
    }
}());
var LinkedList = /** @class */ (function () {
    function LinkedList() {
        *****
}());
exports.LinkedList = LinkedList;
//# sourceMappingURL=linked_list.js.map

and index.js:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var linked_list_1 = require("./linked_list");
var LinkedListStack = /** @class */ (function () {
    function LinkedListStack() {
        *****
}());

//# sourceMappingURL=index.js.map

and i get this error in my browser when i refer my to index.js:

index.ts:1 Uncaught ReferenceError: require is not defined at index.ts:1:1

I have tried to change my tsconfig.json file to "module": "commonjs" but it doesn't work.

If i try to change my "require" and "exports" in js files to "import" and "export" i get this error in the browser:

Uncaught SyntaxError: Cannot use import statement outside a module

These are my: index.html:

<!DOCTYPE html>
<html lang="en">
***
<body>

  <script>const exports = {};</script>
  <script src="js/index.js"></script>
</body>
</html>

and tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
      "outDir": "js",
    "moduleDetection": "force"
  },
  "type": "module"
}
1

There are 1 best solutions below

2
Connor Dooley On

CommonJS is usually used for node.js projects, not in the browser. You probably want "module": "es2015" in your tsconfig.

https://www.typescriptlang.org/tsconfig#module