Switch to TypeScript

Develop 11ty sites with assistance from TypeScript typing.

The project we created in the previous step contains two .js files. Maybe you like TypeScript? Let's switch this project to .ts.

First, of course, add the magical bag of mystery known as the tsconfig.json file. I hope this is right. I always just cut, paste, and pray.

{
	"compilerOptions": {
		"module": "ESNext",
		"target": "ESNext",
		"moduleResolution": "Node",
		"skipLibCheck": true
	},
	"exclude": ["node_modules", "_site"]
}

Next, let's install the tsx package which makes a nice wrapper around esbuild TypeScript, the real star of the show.

We'll also change our build and start scripts to use tsx as a node replacement:

{
	"name": "eleventy-tsx",
	"version": "1.0.0",
	"description": "Demo of Eleventy 3, ESM, and TS/TSX",
	"scripts": {
		"build": "tsx node_modules/@11ty/eleventy/cmd.cjs --config=eleventy.config.ts",
		"start": "tsx node_modules/@11ty/eleventy/cmd.cjs --config=eleventy.config.ts --serve --incremental"
	},
	"keywords": [],
	"author": "Paul Everitt <pauleveritt@me.com>",
	"license": "ISC",
	"type": "module",
	"dependencies": {
		"@11ty/eleventy": "^3.0.0-alpha.6"
	},
	"devDependencies": {
		"prettier": "^3.2.5",
		"tsx": "^4.7.0"
	}
}

Yes, your eyes didn't deceive you -- let's rename our config file to eleventy.config.ts and sprinkle in some TypeScript syntax. 4 characters of syntax (: any) to be precise.

export default function (eleventyConfig: any) {
	return {
		dir: {
			input: "site",
			output: "_site",
		},
	};
}

We must also rename our template to site/index.11ty.ts and a return type:

export function render(): string {
	return "<h1>Hello ESM</h1>";
}

We run our dev server and... wump, we have a problem. No files written:

[11ty] Wrote 0 files in 0.01 seconds (v3.0.0-alpha.4)

We need to return to eleventy.config.ts and teach it about .ts files. We'll go ahead and teach about .tsx as well.

export default function (eleventyConfig: any) {
	eleventyConfig.addExtension(["11ty.jsx", "11ty.ts", "11ty.tsx"], {
		key: "11ty.js",
	});

	return {
		dir: {
			input: "site",
			output: "_site",
		},
	};
}

This time when we build -- success!

[11ty] Writing ./_site/index.html from ./site/index.11ty.ts
[11ty] Wrote 1 file in 0.02 seconds (v3.0.0-alpha.6)
[11ty] Watching…
[11ty] Server at http://localhost:8080/