There are two .ts files in my project:
linked_list.ts
class Node {
*****
}
class LinkedList{
*****
}
export {LinkedList};
and index.ts:
import {LinkedList} from "./linked_list";
class LinkedListStack{
*****
}
After compilation, they become:
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
An error occurs in the browser when trying to reference index.js:
index.ts:1 Uncaught ReferenceError: require is not defined at index.ts:1:1
I have attempted to modify my tsconfig.json file by setting "module": "commonjs" but it does not resolve the issue.
If I change "require" and "exports" in js files to "import" and "export", a different error arises in the browser:
Uncaught SyntaxError: Cannot use import statement outside a module
The relevant files include: index.html:
<!DOCTYPE html>
<html lang="en">
***
<body>
<script>const exports = {};</script>
<script src="js/index.js"></script>
</body>
</html>
as well as tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"sourceMap": true,
"outDir": "js",
"moduleDetection": "force"
},
"type": "module"
}