Yarn 2 (berry), Typescript, VSCode, Prettier, ESLint and Fastify

#it #javascript

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-project
cd my-project
yarn init
yarn add fastify typescript ts-node
yarn add @types/node eslint prettier -D

VSCode configuration _

The documentation: https://yarnpkg.com/advanced/editor-sdks

yarn add @yarnpkg/pnpify

Install SDK.

yarn pnpify --sdk
Cleaning up the existing SDK files...
Installing fresh SDKs for /Users/eshlox/projects/my-project:

✓ Eslint
✓ Prettier
✓ Typescript

Open the project in VSCode.

  1. Press Ctrl+Shift+P in a TypeScript file.
  2. Choose "Select TypeScript Version".
  3. 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.