Template engines are used when you want to rapidly build web
applications that are split into different pages. Templates
also enable fast rendering of the server-side data that needs
to be passed to the application. You can use Ink, TypeScript
and the native Node.js HTTP server to serve up HTML documents
from the server-side.
First, create a project with the following structure and files.
src/index.ts
src/page.ink
package.json
src
index.ts
page.ink
package.json
import http from 'http';
import ink from '@stackpress/ink/compiler';
//create ink compiler
const compiler = ink({ cwd: __dirname });
//create http server
const server = http.createServer(async (req, res) => {
//if build asset...
if (req.url?.startsWith('/build/')) {
//get filename ie. abc123.js
const filename = req.url.substring(7);
//get asset
const { type, content } = await compiler.asset(filename);
//send response
res.writeHead(200, { 'Content-Type': type });
return res.end(content);
//if home page
} else if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
return res.end(await compiler.render('./index.ink', {
title: 'Hello World'
}));
}
});
//listen on port 3000
server.listen(3000);
<style>
.title { text-align: center; }
</style>
<script>
import { env, props } from '@stackpress/ink';
const { BUILD_ID, APP_DATA } = env();
const { title } = props();
</script>
<html>
<head>
<title>{title}</title>
<link rel="stylesheet" type="text/css" href={`/build/${BUILD_ID}.css`} />
<script data-app={APP_DATA} src={`/build/${BUILD_ID}.js`}></script>
</head>
<body>
<h1 class="title">{title}</h1>
</body>
</html>
{
"name": "my-project",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "ts-node ./src/index.ts"
},
"dependencies": {
"@stackpress/ink": "0.3.23"
},
"devDependencies": {
"@stackpress/ink-dev": "0.3.23",
"@types/node": "22.1.0",
"ts-node": "10.9.2",
"typescript": "5.5.4"
}
}
The server file
src/index.ts
implements a simple server utilizing the Ink compiler in
its most simplistic form. The document file
src/page.ink
is using the most basic Ink syntax. To test the script and
see the results, run the following command in terminal.
npm run dev
Load
http://localhost:3000/
in your browser to see your application.