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.
Initialize a new project
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!
Install packages
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
Toggle esModuleInterop
In you tsconfig under compiler options set the esModuleInterop to 'true'
Setup your server
Setup your typescript server. I'm calling mine server.ts and for this example it will be located inside the src directory
Edit package.json
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.
Run it!
And finally all we have to do is run our script. And we're all good to go!
Top comments (3)
Can you not use screenshots for the code snippets? I want my AI to look at this but screenshots are a bad way of showing code these days.
how can I get my vite project to communicate with my local server/backend.... I keep getting 404. I have tried to set up proxies and the likes
As I don't have your project in front of me this what I suggest you check.
Client side code and Server side code should be separated into two different directories.
Make sure your client is running on one port, and your server should be running on another
Make sure the base url you are making the request to has 'https://' at the beginning
Your frontend should be making a request via the fetch api or axios with it's endpoint as the port that your server is running on. If your server is running on port 3000 then...
sometimes it might be that trailing backslash is preventing you from hitting the root endpoint of '/', meaning you might be trying to access 'localhost:3000//' and that's why you are getting a 404