Once you have your Node installed let's set up our project folder and install the basic dependencies.
In your terminal type
mkdir NodeProject
The above command will create a folder named NodeProject.
Next, run the command to initiate a node project
cd NodeProject
npm init --y
This command will create a package.json file that holds information about your project and its dependencies.
Next, let's install the dependencies
npm install express
The above command will install the express packages which is a web framework and will allow us to create a server.
Next, let's install some dev dependencies.
npm install -D nodemon
Now let's add nodemon to our package.json scripts. In your pakage.json file look for scripts and add the below line
"start": "node server.js",
"server": "nodemon server.js"
Creating our node server
Inside your NodeProject folder let's create our server. First, create a folder with the name src.
mkdir src
Inside the src folder create a server.js file
cd src
touch server.js
Inside the server.js file write the below code
const express = require("express");
const PORT = 5000;
// Initialize express app
const app = express();
// Middleware to grab request body
app.use(express.json());
app.use(
express.urlencoded({
extended: false,
}),
);
app.get('/', (req, res) => {
res.status(200)json({
message: 'Server is up and running',
});
});
app.listen(PORT, () => {
console.log(`Server running at port ${PORT}`);
});
Once you have your server.js file ready save it and run the below command on your terminal to spin up the server.
npm run server
You will see a similar response on the console.
Now open chrome and head over to the url localhost:5000 and you will see a message "server is up and running".
Congratulations your express server is ready.
Next, let's set up eslint and prettier.
Setting up ESLint and Prettier
Adding ESLint
Press Ctrl + C to close the server.
Now run the following command to install eslint as a dev dependency.
npm install eslint --save-dev
npm init @eslint/config
Adding Prettier
Run the following command to install the prettier dependency.
npm install -D prettier
Create a .prettierrc.json file at the root of your project folder and add the below code
{
"semi": true,
"singleQuotes": true,
"tabWidth": 4,
"bracketSpacing": false,
"arrowParens": "always"
}
You can customize the values according to your needs.
Configuring prettier with eslint
Install the below dependency
npm install -D eslint-config-prettier
Lastly, create a folder with the name .vscode and inside that create a file settings.json and add the below JSON code.
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
}
Adding the above code will allow you to format your code according to the rules that you have provided in your eslint and prettier configurations with just a Ctrl + S.
Comments
Post a Comment