In three simple steps, I will show you how to set up your server.
Steps
- Create a folder called 'typescript-server'
- Create
src
folder inside 'typescript-server' and create index.ts file. - cd into the typescript-server folder and initialize your project by running;
Before we go on please add the following code we will be testing on into the index.ts file
console.log("Hello, Dev.to");
So that anytime we run our code we will be seeing some output on the console.
npm init -y
the above code will create a package.json file that will hold all your dependencies for the project.
- install the needed dependencies:
yarn add -D @types/node
yarn add -D typescript
yarn add -D ts-node
yarn add -D nodemon
or you install all of them once
yarn add -D @types/node typescript ts-node nodemon
- Create the ts config by running;
npx tsconfig.json
at the terminal, some options will pop up asking you to select which platform are you using, select node.
- open your package.json file and add the following code under the script tag
"watch": "tsc -w",
then your package.json will look like this
{
"name": "lireddit-server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch": "tsc -w",
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/node": "^14.14.20",
"nodemon": "^2.0.7",
"ts-node": "^9.1.1",
"typescript": "^4.1.3"
}
}
to test if what we have done so far is correct, now run the app with yarn watch
. Note, you must have npm, and yarn install in your system to avoid any complexity.
To use the Installed nodemon
you need to add another line onto your script section in the package.json file. Now add the follow to your package.json file;
"dev": "nodemon dist/index.js",
I know you will be wondering where do we have the dist/index.js
from, don't worry about it. when you run the yarn watch, it compiles and generates a dist/index.js
file.
For us to have all the different ways of running our project, I will just go ahead and add all the run scripts for you. after adding all the run script, this is how your package.json will look like now.
{
"name": "lireddit-server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch": "tsc -w",
"dev": "nodemon dist/index.js",
"devIn": "nodemon --exec ts-node src/index.ts",
"start": "node dist/index.js",
"startIn": "ts-node src/index.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/node": "^14.14.20",
"nodemon": "^2.0.7",
"ts-node": "^9.1.1",
"typescript": "^4.1.3"
}
}
You can now run your app using the following commands;
yarn watch
yarn dev
yarn devIn
yarn start
yarn startIn
Thank you for reading this little piece of my typescript set up!
Top comments (0)