liveBook · Manning

Type property

As explained in Essential TypeScript 5, Third Edition

The type property is a package.json setting that declares the module system used by a JavaScript package.

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

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Explains values, compiler coordination, import extensions, and filename alternatives, but defers the underlying reasons to later module treatment.
Examples
Uses todo, primer, tools, and types projects with package.json entries, Node16 configurations, and .js import paths.
What it assumes
Assumes package.json, tsconfig.json, TypeScript compilation, and basic import usage; distinguishes ECMAScript modules from CommonJS.
What you can do after
Operate/configure a TypeScript Node.js project with a selected module format and runtime-compatible import paths.
How it connects
Connects package.json, TypeScript compiler configuration, ECMAScript modules, CommonJS, Node.js, and import statements.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.