A boilerplate Node.js config
Here is a simple boilerplate configuration when using Node.js with Typescript using ES-modules and reloading it with Nodemon.
The configuration
package.json
{
"main": "index.ts",
"type": "module",
"scripts": {
"watch": "tsc -w",
"dev": "nodemon"
},
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2"
},
"devDependencies": {
"@types/cors": "^2.8.13",
"@types/express": "^4.17.15",
"nodemon": "^2.0.20",
"typescript": "^4.9.4"
}
}
As TypeScript is globally installed on my VS Code IDE, there is no need to add it as a devDependency, but you should if you do not have it installed at all.
tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"rootDir": "./src",
"moduleResolution": "NodeNext",
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"baseUrl": "./",
"outDir": "./dist",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"strictNullChecks": true,
"alwaysStrict": true,
"noImplicitReturns": true,
"skipLibCheck": true,
"jsx": "react-jsx"
},
"include": ["./src/**/*.ts"],
"exclude": ["node_modules"],
}
nodemon.json
{
"watch": ["dist"],
"ext": "js,json",
"ignore": [],
"exec": "node ./dist/index.js"
}
The execution
Having your project run is done in two-and-a-half steps.
- We must compile TypeScript into JavaScript..
.. (and tell it to re-compile every time we save a change in our TypeScript-files)
// execute in a terminal-window
npm run watch
// it will do whatever "watch" is told to do in package.json
- We must tell Nodemon to run our app..
.. (and tell it to re-run it every time it notices that any .js or .json file has been changed)
// execute in a new terminal-window
npm run nodemon
// it will do whatever nodemon.json has stated
25 december 2022