I am new to Typescript, but pretty well versed in JS. My question is how do I use modules to write my TS, and remove the modules when exporting to JS?
With normal JS, I can split functionality into many files, like so:
//func.js
function add(a, b) {
return a+b
}
//other.js
(function(){
console.log(add(1, 2))
})
Assuming that func.js is loaded when this is ran, this should work.
With TS though, things get interesting:
//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))
})
When compiled down to individual JS files, it produces this:
//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 would be nice if browsers (like mine) understood how to do this. Maybe I am doing this wrong? What I want in the end though is to have the TS files look similar to what they would look like had they been written in plain JS (that is, to not use modules, but to assume that the functions will be there by the time they are executed).
My tsconfig.json:
{
"compilerOptions": {
"target": "ESNEXT",
"lib": ["ES2015", "dom"],
"module": "commonjs",
"outDir": "js/",
"rootDir": "ts/",
"strictNullChecks": false,
"baseUrl": "./",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
},
"include": [
"./ts/*"
]
}
File tree:
./js
./js/func.js
./js/other.js
./ts
./ts/func.ts
./ts/other.ts
./tsconfig.json
Edit: I am using JS in a browser environment, not Node. I want the benefits of TS, except for modules. Modules (imports, exports) are needed to link the TS files together, but I cannot have modules in the final JS (many browsers dont support it). What I want is to have the final JS to have the compiled code, minus module functionality.
I figured out what I needed to do to get what I had working.
Basically, I was using import and export syntax when I didn't need to. Using "module": "none" did what I want, but I had to remove the import and exports from my code. Then, everything compiled as expected!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With