An ECMAScript module lets an application split code across files while making dependencies explicit. It is the standard JavaScript module format and is generally the choice for a project when its runtime supports it. CommonJS is an older alternative; an ECMAScript module can import from a CommonJS module. section 4.5
Export a function and use it
In tax.js, `export default function(price) { return Number(price) * 1.2; }` makes the function available outside the file. In index.js, `import calcTax from "./tax.js";` gives that default export a local name. Calling `calcTax(100)` returns `120`. Other contents of a module are not available to importing files unless exported. section 4.5.2 section 4.5.3
Use named exports to share several related features: `export function applyDiscount(product, discount = 5) { ... }` can be imported with `import { applyDiscount } from "./utils.js";`. The braces name the features needed. A path beginning with `./` or `../` refers to a project file; a location without that prefix denotes a nonlocal dependency, whose resolution depends on the tools in use. section 4.5.5 section 4.5.3
For a TypeScript project running its generated JavaScript in Node.js:
- Set `"type": "module"` in package.json so Node.js treats the project’s JavaScript files as ECMAScript modules. section 2.3.1 section 4.5.1
- Use the compiler setting `"module": "Node16"` when the compiler needs to determine the module format from package.json. section 2.3.1
- Write the generated JavaScript extension in relative TypeScript imports: `import { sum } from "./calc.js";`, even though the source file is calc.ts. Omitting the extension is a problem for Node.js ECMAScript modules. section 2.3.1 section 5.8
Module configuration must agree with the emitted code. When TypeScript preserves `import` and `export` in generated JavaScript but Node.js has not been told to use ECMAScript modules, execution fails with `Cannot use import statement outside a module`. Set the project’s module type and check relative import extensions before treating this as an error in the exported function. section 5.8


































