Scripts
To automatically build and run your Fastify server in watch mode, you can use tsc for compilation and nodemon to watch for changes and restart the server automatically. Below are the steps and script commands to set this up.
Step 1: Install Required Development Dependencies
- Nodemon: A tool that helps with auto-restarting the server whenever file changes in the directory are detected.
- TypeScript: For compiling
.tsfiles to.js.
Run the following command to install nodemon and TypeScript as development dependencies:
npm install -D nodemon typescriptStep 2: Configure TypeScript for Incremental Builds
Ensure your tsconfig.json is set up for incremental builds by including the outDir option, which specifies where compiled JavaScript files will be placed, and enabling watch mode:
{ "compilerOptions": { "target": "ES2020", "module": "commonjs", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "outDir": "./dist", "rootDir": "./src" }, "include": ["src/**/*.ts"]}Step 3: Update Project Structure
Organize your project with the following structure to maintain clean code separation:
/my-microservice│├── /src│ └── server.ts # Main server file│├── /dist # Compiled JavaScript output├── tsconfig.json # TypeScript configuration└── package.json # Project configurationStep 4: Add Scripts to package.json
Add the following scripts to your package.json to build, watch, and run the server:
"scripts": { "build": "tsc", // Compile TypeScript to JavaScript "start": "node dist/server.js", // Run the compiled JavaScript server "dev": "nodemon --watch 'src/**/*.ts' --exec 'tsc && node dist/server.js'" // Watch and auto-restart}Step 5: Running the Server in Watch Mode
Use the dev script to run the server in auto watch mode:
npm run devHow the dev Command Works:
-
Nodemon Watches Files: The command watches for changes in any
.tsfile inside thesrcfolder. -
Compile and Restart: When a change is detected,
nodemonfirst compiles the TypeScript code usingtsc, then runs the compiled JavaScript using NodeJS. -
Auto-Restart: If any file changes, the server automatically stops and restarts, reflecting the latest changes without requiring manual intervention.
Additional Customization (Optional):
-
Custom
nodemon.json: You can create anodemon.jsonfile to further customize hownodemonbehaves:{"watch": ["src"],"ext": "ts","exec": "tsc && node dist/server.js","ignore": ["dist"]} -
Use
ts-node: If you prefer not to compile manually every time, you can directly run TypeScript files usingts-node(requirests-nodepackage):Terminal window npm install -D ts-nodeModify the
devscript to:"dev": "nodemon --watch 'src/**/*.ts' --exec 'ts-node src/server.ts'"
This setup will streamline your development workflow, allowing you to focus on coding without needing to manually build and restart the server each time you make a change. Let me know if you need any adjustments or further guidance!