I recently started learning Typescript, although I am proficient in JS. My inquiry pertains to utilizing modules in TS for coding purposes and then excluding the modules when converting to JS.
In traditional JS, I segment functionalities into different files as follows:
//func.js
function add(a, b) {
return a+b
}
//other.js
(function(){
console.log(add(1, 2))
})
Assuming that func.js is loaded, this setup should function correctly.
However, working with TS introduces some interesting aspects:
//func.ts
export function add(a: number, b: number): number {
return a+b
}
//other.ts
import { add } from "./func";
(function(){
console.log(add(1, 2))
})
Upon compiling individual JS files, the output appears as:
//func.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function add(a, b) {
return a + b;
}
exports.add = add;
//other.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var func_1 = require("./func");
(function () {
console.log(func_1.add(1, 2));
});
This approach works well if browsers are compatible. Could there be a mistake in my implementation? My ultimate goal is to have TS code resembling plain JS without using modules, ensuring functions are present before execution.
Here's my tsconfig.json configuration:
{
"compilerOptions": {
"target": "ESNEXT",
"lib": ["ES2015", "dom"],
"module": "commonjs",
"outDir": "js/",
"rootDir": "ts/",
"strictNullChecks": false,
"baseUrl": "./",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
},
"include": [
"./ts/*"
]
}
Directory structure:
./js
./js/func.js
./js/other.js
./ts
./ts/func.ts
./ts/other.ts
./tsconfig.json
Edit: I'm utilizing JS in a browser environment, not Node. I aim to leverage TS advantages, except for modules. While modules are necessary to connect TS files, they must be excluded in the final JS (as many browsers do not support them). I desire the compiled JS code to discard module functionality.