TypeScript
Compilation
Use tsc -w to compile a file, when its content changed, but it only compiles this one file even if build/ folder is empty.
Alternatively you can compile with tsc.
Module
Configuration
- tsconfig.json::module should be “commonjs”.
<script src="build/main.js" type="module"></script>
CommonJS
Export:
module.exports.myFunc = function() {
return "Hello World!";
}
Import:
const {myFunc} = require('./MyFunc') // Can be called anywhere (e.g. inside if statement)
console.log(myFunc()) // "Hello World!"
ES (ECMAScript)
Export:
export function myFunc = {
return "Hello World!";
}
Import:
import {myFunc} from './MyFunc.js'; // must be at the top; You have to append .js, otherwise file is not found.
console.log(myFunc()) // "Hello World!"
CommonJS vs ES
| CommonJS | ES |
|---|---|
| Old feature | New feature (not usable in earlier Node.js versions) |
| module.exports & require | export & import |
| Can be called anywhere | Can only be called at the top |
| synchronous loading (program must wait) | asynchronous loading |