Require this, require that... ugh! It's 2022 man!
I remember setting up my server for the first time with typescript while trying to use import and export statements... my god that was a painful day.
So I'm here to save you all that trouble and show you how you can setup a typescript server super easily with ES6 import statements. We're going to use Vite to bypass all that boring setup, and get straight to the meat of things.
First cd into the folder where you keep your projects and run this command to intialize a new Vite project. Follow the prompts and select react and typescript. CD into you project and run the command
yarn install to install all the dependancies. And we're off to the races!
First things first we need a few packages.
- Express framework itself
- The types for our express objects
- ts-node which allows us to run our server in node.js without having to precompile
- and nodemon which will restart our server every time we make a change
In you tsconfig under compiler options set the esModuleInterop to 'true'
Setup your typescript server. I'm calling mine server.ts and for this example it will be located inside the src directory
In you package.json add "type": "module" (if its not already there) to enable ES6 import syntax, and set your nodemon script with the filepath to your server.
And finally all we have to do is run our script. And we're all good to go!