TypeScript
Greenwood provides built-in support for TypeScript, either through type-stripping (default behavior) or with the ability to fallback to using the TypeScript compiler if you're leveraging certain transformation based TypeScript features (like enums
and namespaces
(opens in a new window)) or JavaScript syntax like Decorators. If you need these additional capabilities, you can set the useTsc
option in your Greenwood configuration file.
You can read this guide (opens in a new window) to learn more about running TypeScript with NodeJS, including the
--experimental-transform-types
(opens in a new window) flag. You can see an example Greenwood TypeScript repo here (opens in a new window).
Setup
The below steps will help you get up and running with TypeScript in your Greenwood project. The general recommendation is to use type-stripping during development for faster live reload, and then run TypeScript during CI (e.g. GitHub Actions) to check and enforce all types, e.g. tsc --project tsconfig.json
.
- You will need to use Node >= 22.6.0 and set the
--experimental-strip-types
flag - Install TypeScript into your project, e.g.
npm i typescript --save-dev
- Create a tsconfig.json file at the root of your project with these minimum configuration settings. We recommend adding the
erasableSyntaxOnly
setting (opens in a new window)
{
"compilerOptions": {
"module": "preserve",
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": false,
"noEmit": true
}
}
If you're feeling adventurous, you can use >=23.x and omit the
--experimental-strip-types
flag. Keep an eye on this PR (opens in a new window) for when unflagged type-stripping support may come to Node LTS 22.x. 👀
Types
Configuration
In addition to being able to author your components, SSR pages, and API routes in TypeScript, you can also author your configuration file (and plugins) in TypeScript by using a greenwood.config.ts file.
import type { Config } from '@greenwood/cli';
const config: Config = {
// ...
}
export default config;
See our reference docs on Greenwood's available types for more information on authoring with TypeScript.
Import Attributes
Currently TypeScript does not support types for standard JSON and CSS Import Attributes (opens in a new window). You can use the below snippets as a reference for providing these types for your own project in the meantime.
declare module "*.css" {
const sheet: CSSStyleSheet;
export default sheet;
}
declare module "*.json" {
const data: object;
export default data;
}