Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
doc: move ts doc to standalone page
Author:     Marco Ippolito <marcoippolito54@gmail.com>
Co-authored-by:    Geoffrey Booth <webadmin@geoffreybooth.com>
Date:      Tue Jul 23 21:03:39 2024 -0700
  • Loading branch information
marco-ippolito and GeoffreyBooth committed Jul 24, 2024
commit f6d38e4cd16d2b538056f27216c8927f0b091aad
2 changes: 1 addition & 1 deletion doc/api/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -3434,7 +3434,7 @@ node --stack-trace-limit=12 -p -e "Error.stackTraceLimit" # prints 12
[ScriptCoverage]: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#type-ScriptCoverage
[ShadowRealm]: https://github.com/tc39/proposal-shadowrealm
[Source Map]: https://sourcemaps.info/spec.html
[TypeScript type-stripping]: module.md#typescript-support
[TypeScript type-stripping]: typescript.md#type-stripping
[V8 Inspector integration for Node.js]: debugger.md#v8-inspector-integration-for-nodejs
[V8 JavaScript code coverage]: https://v8project.blogspot.com/2017/12/javascript-code-coverage.html
[V8 code cache]: https://v8.dev/blog/code-caching-for-devs
Expand Down
1 change: 1 addition & 0 deletions doc/api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
* [Modules: ECMAScript modules](esm.md)
* [Modules: `node:module` API](module.md)
* [Modules: Packages](packages.md)
* [Modules: TypeScript](typescript.md)
* [Net](net.md)
* [OS](os.md)
* [Path](path.md)
Expand Down
120 changes: 0 additions & 120 deletions doc/api/module.md
Original file line number Diff line number Diff line change
Expand Up @@ -1050,121 +1050,6 @@ returned object contains the following keys:
* columnNumber: {number} The 1-indexed columnNumber of the
corresponding call site in the original source

## TypeScript support

<!--lint disable prohibited-strings-->

<!-- YAML
added: REPLACEME
-->

> Stability: 1.0 - Early development

The flag [`--experimental-strip-types`][] enables Node.js to run TypeScript
files that contain only type annotations. Such files contain no TypeScript
features that require transformation, such as enums or namespaces. Node.js will
replace inline type annotations with whitespace, and no type checking is
performed. TypeScript features that depend on settings within `tsconfig.json`,
such as paths or converting newer JavaScript syntax to older standards, are
intentionally unsupported.

To get fuller TypeScript support, including support for enums and namespaces
and paths, see <https://nodejs.org/en/learn/getting-started/nodejs-with-typescript>.
The built-in TypeScript support is designed to be lightweight and as fast as
possible. By intentionally not supporting syntaxes that require JavaScript code
generation, and by replacing stripped types with whitespace, Node.js can run
TypeScript code without the need for source maps and with less overhead.

### Determining module system

Node.js supports both [CommonJS][] and [ES Modules][] syntax in TypeScript
files. Node.js will not convert from one module system to another; if you want
your code to run as an ES module, you must use `import` and `export` syntax,
and if you want your code to run as CommonJS you must use `require` and
`module.exports`.

* `.ts` files will have their module system determined
[the same way as `.js` files.][] To use `import` and `export` syntax, add
`"type": "module"` to the nearest parent `package.json`.
* `.mts` files will always be run as ES modules, similar to `.mjs` files.
* `.cts` files will always be run as CommonJS modules, similar to `.cjs` files.
* `.tsx` files are unsupported.

As in JavaScript files, [file extensions are mandatory][] in `import` statements
and `import()` expressions: `import './file.ts'`, not `import './file'`.
Because of backward compatibility, file extensions are also mandatory in
`require()` calls: `require('./file.ts')`, not `require('./file')`, similar to
how the `.cjs` extension is mandatory in `require` calls in CommonJS files.

The `tsconfig.json` option `allowImportingTsExtensions` will allow the
TypeScript compiler `tsc` to type-check files with `import` specifiers that
include the `.ts` extension.

### Unsupported TypeScript features

Since Node.js is only removing inline types, any TypeScript features that
involve _replacing_ TypeScript syntax with new JavaScript syntax will error.
This is by design. To run TypeScript with such features, see
<https://nodejs.org/en/learn/getting-started/nodejs-with-typescript#running-typescript-code-in-nodejs>

The most prominent unsupported features that require transformation are:

* `Enum`
* `experimentalDecorators`
* `namespaces`
* parameter properties

In addition, Node.js does not read `tsconfig.json` files and does not support
features that depend on settings within `tsconfig.json`, such as paths or
converting newer JavaScript syntax into older standards.

### Importing types without `type` keyword

Due to the nature of type stripping, the `type` keyword is necessary to
correctly strip type imports.
Without the `type` keyword, Node.js will treat the import as a value import,
which will result in a runtime error.
The tsconfig option [`verbatimModuleSyntax`][] can be used to match this behavior.

This example will work correctly:

```ts
import type { Type1, Type2 } from './module.ts';
import { fn, type FnParams } from './fn.ts';
```

This will result in a runtime error:

```ts
import { Type1, Type2 } from './module.ts';
import { fn, FnParams } from './fn.ts';
```

### Type stripping in `node_modules` directories

To avoid encouraging package authors to publish TypeScript only modules,
Node.js will by default refuse to handle TypeScript files inside `node_modules` directories.
When attempting to resolve a `.ts`, `.cts`, or `.mts` file that is a children of a
`node_modules` directory, `defaultResolve` will throw
a [`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`][] error.

### Non-file forms of input

Type stripping can be enabled for `--eval` and STDIN input. The module system
will be determined by `--input-type`, as it is for JavaScript.

TypeScript syntax is unsupported in the REPL, `--print`, `--check`, and
`inspect`.

### Source maps

Since inline types are replaced by whitespace, source maps are unnecessary for
correct line numbers in stack traces; and Node.js does not generate them. For
source maps support, see
<https://nodejs.org/en/learn/getting-started/nodejs-with-typescript#running-typescript-code-in-nodejs>

<!--lint enable prohibited-strings-->

[CommonJS]: modules.md
[Conditional exports]: packages.md#conditional-exports
[Customization hooks]: #customization-hooks
Expand All @@ -1173,9 +1058,7 @@ source maps support, see
[Source map v3 format]: https://sourcemaps.info/spec.html#h.mofvlxcwqzej
[`"exports"`]: packages.md#exports
[`--enable-source-maps`]: cli.md#--enable-source-maps
[`--experimental-strip-types`]: cli.md#--experimental-strip-types
[`ArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
[`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`]: errors.md#err_unsupported_node_modules_type_stripping
[`NODE_V8_COVERAGE=dir`]: cli.md#node_v8_coveragedir
[`SharedArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer
[`SourceMap`]: #class-modulesourcemap
Expand All @@ -1186,14 +1069,11 @@ source maps support, see
[`register`]: #moduleregisterspecifier-parenturl-options
[`string`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
[`util.TextDecoder`]: util.md#class-utiltextdecoder
[`verbatimModuleSyntax`]: https://www.typescriptlang.org/tsconfig/#verbatimModuleSyntax
[chain]: #chaining
[file extensions are mandatory]: esm.md#mandatory-file-extensions
[hooks]: #customization-hooks
[load hook]: #loadurl-context-nextload
[module wrapper]: modules.md#the-module-wrapper
[prefix-only modules]: modules.md#built-in-modules-with-mandatory-node-prefix
[realm]: https://tc39.es/ecma262/#realm
[source map include directives]: https://sourcemaps.info/spec.html#h.lmz475t4mvbx
[the same way as `.js` files.]: packages.md#determining-module-system
[transferrable objects]: worker_threads.md#portpostmessagevalue-transferlist
153 changes: 153 additions & 0 deletions doc/api/typescript.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
# Modules: TypeScript

## Enabling

There are two ways to enable runtime TypeScript support in Node.js:

1. For [full support][] of all of TypeScript's syntax and features, including
using any version of TypeScript, use a third-party package.

2. For lightweight support, you can use the built-in support for
[type stripping][].

## Full TypeScript support

To use TypeScript with full support for all TypeScript features, including
`tsconfig.json`, you can use a third-party package. These instructions use
[`tsx`][] as an example but there are many other similar libraries available.

1. Install the package as a development dependency using whatever package
manager you're using for your project. For example, with `npm`:

```bash
npm install --save-dev tsx
```

2. Then you can run your TypeScript code via:

```bash
npx tsx your-file.ts
```

Or alternatively, you can run with `node` via:

```bash
node --import=tsx your-file.ts
```

## Type stripping

<!-- YAML
added: REPLACEME
-->

> Stability: 1.0 - Early development

The flag [`--experimental-strip-types`][] enables Node.js to run TypeScript
Comment thread
marco-ippolito marked this conversation as resolved.
files that contain only type annotations. Such files contain no TypeScript
features that require transformation, such as enums or namespaces. Node.js will
replace inline type annotations with whitespace, and no type checking is
performed. TypeScript features that depend on settings within `tsconfig.json`,
such as paths or converting newer JavaScript syntax to older standards, are
intentionally unsupported. To get fuller TypeScript support, including support
for enums and namespaces and paths, see [Full TypeScript support][].

The type stripping feature is designed to be lightweight.
By intentionally not supporting syntaxes that require JavaScript code
generation, and by replacing inline types with whitespace, Node.js can run
TypeScript code without the need for source maps.

### Determining module system

Node.js supports both [CommonJS][] and [ES Modules][] syntax in TypeScript
files. Node.js will not convert from one module system to another; if you want
your code to run as an ES module, you must use `import` and `export` syntax, and
if you want your code to run as CommonJS you must use `require` and
`module.exports`.

* `.ts` files will have their module system determined [the same way as `.js`
files.][] To use `import` and `export` syntax, add `"type": "module"` to the
nearest parent `package.json`.
* `.mts` files will always be run as ES modules, similar to `.mjs` files.
* `.cts` files will always be run as CommonJS modules, similar to `.cjs` files.
* `.tsx` files are unsupported.

As in JavaScript files, [file extensions are mandatory][] in `import` statements
and `import()` expressions: `import './file.ts'`, not `import './file'`. Because
of backward compatibility, file extensions are also mandatory in `require()`
calls: `require('./file.ts')`, not `require('./file')`, similar to how the
`.cjs` extension is mandatory in `require` calls in CommonJS files.

The `tsconfig.json` option `allowImportingTsExtensions` will allow the
TypeScript compiler `tsc` to type-check files with `import` specifiers that
include the `.ts` extension.

### Unsupported TypeScript features

Since Node.js is only removing inline types, any TypeScript features that
involve _replacing_ TypeScript syntax with new JavaScript syntax will error.
This is by design. To run TypeScript with such features, see
[Full TypeScript support][].

The most prominent unsupported features that require transformation are:

* `Enum`
* `experimentalDecorators`
* `namespaces`
* parameter properties

In addition, Node.js does not read `tsconfig.json` files and does not support
features that depend on settings within `tsconfig.json`, such as paths or
converting newer JavaScript syntax into older standards.

### Importing types without `type` keyword

Due to the nature of type stripping, the `type` keyword is necessary to
correctly strip type imports. Without the `type` keyword, Node.js will treat the
import as a value import, which will result in a runtime error. The tsconfig
option [`verbatimModuleSyntax`][] can be used to match this behavior.

This example will work correctly:

```ts
import type { Type1, Type2 } from './module.ts';
import { fn, type FnParams } from './fn.ts';
```

This will result in a runtime error:

```ts
import { Type1, Type2 } from './module.ts';
import { fn, FnParams } from './fn.ts';
```

### Non-file forms of input

Type stripping can be enabled for `--eval` and STDIN input. The module system
will be determined by `--input-type`, as it is for JavaScript.

TypeScript syntax is unsupported in the REPL, `--print`, `--check`, and
`inspect`.

### Source maps

Since inline types are replaced by whitespace, source maps are unnecessary for
correct line numbers in stack traces; and Node.js does not generate them. For
source maps support, see [Full TypeScript support][].

### Type stripping in dependencies

To discourage package authors from publishing packages written in TypeScript,
Node.js will by default refuse to handle TypeScript files inside folders under
a `node_modules` path.

[CommonJS]: modules.md
[ES Modules]: esm.md
[Full TypeScript support]: #full-typescript-support
[`--experimental-strip-types`]: cli.md#--experimental-strip-types
[`tsx`]: https://tsx.is/
[`verbatimModuleSyntax`]: https://www.typescriptlang.org/tsconfig/#verbatimModuleSyntax
[file extensions are mandatory]: esm.md#mandatory-file-extensions
[full support]: #full-typescript-support
[the same way as `.js` files.]: packages.md#determining-module-system
[type stripping]: #type-stripping