Let’s configure Fastify project with Yarn 2, Typescript, VSCode, Prettier and ESLint.
Install Yarn 2 / berry
The documentation: https://yarnpkg.com/getting-started
I assume you have the latest Yarn version (at least v1.22).
yarn set version berry
Initialize the repository
mkdir my-projectcd my-projectyarn inityarn add fastify typescript ts-nodeyarn add @types/node eslint prettier -D
VSCode configuration
The documentation: https://yarnpkg.com/advanced/editor-sdks
yarn add @yarnpkg/pnpify
Install SDK.
❯ yarn pnpify --sdkCleaning up the existing SDK files...Installing fresh SDKs for /Users/eshlox/projects/my-project:
✓ Eslint ✓ Prettier ✓ Typescript
Open the project in VSCode.
- Press
Ctrl+Shift+P
in a TypeScript file. - Choose “Select TypeScript Version”.
- Pick “Use Workspace Version”.
package.json
Add the start
script to the package.json
file.
"scripts": { "start": "ts-node index.ts" },
TS config
Create Typescript configuration file.
yarn tsc --init -t ES2020
Simple API endpoint
Add the code to the index.ts
file.
import fastify from "fastify";
const server: fastify.FastifyInstance = fastify({});
const opts: fastify.RouteShorthandOptions = { schema: { response: { 200: { type: "object", properties: { pong: { type: "string", }, }, }, }, },};
server.get("/ping", opts, async (request, reply) => { return { pong: "it worked!" };});
server.listen(3000, (err) => { if (err) { server.log.error(err); process.exit(1); }
server.log.info(`Server listening on port 3000.}`);});
Run and test the project
yarn start
The API should be available at http://localhost:3000/ping
.