The package.json type property selects the module system that Node.js uses for a JavaScript package. Set it to "module" for ECMAScript modules or "commonjs" for CommonJS modules. section 4.5.1 section 5.8
Listing 2.28 Adding a configuration property in the package.json file in the todo folder
{
"name": "todo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module"
}
A minimal todo package.json declares ECMAScript modules with "type": "module". section 2.3.1
When TypeScript relies on package.json to determine the module format, configure tsconfig.json with "module": "Node16". With ECMAScript modules, imports must name the generated JavaScript file, such as "./todoItem.js", rather than the TypeScript source file. section 2.3.1 section 5.8
TypeScript project using ECMAScript modules
In package.json, add "type": "module". In tsconfig.json, use "module": "Node16". Then write imports against emitted JavaScript: import { sum } from "./calc.js";. Running the emitted file as a module avoids the "Cannot use import statement outside a module" error. section 5.8
Keep these constraints in mind:
- Use "module" or "commonjs" as the type value to choose the package module format. section 4.5.1
- Use .mjs and .cjs as JavaScript alternatives, or .mts and .cts as TypeScript alternatives, when choosing the format by filename instead. section 5.8
- Include the .js extension in imports when compiling TypeScript for Node.js ECMAScript modules. section 2.3.1
