A simple website using routing & EJS

A simple website using routing & EJS

In Lesson 4, let’s create a simple website using EJS (Embedded JavaScript) as the templating engine and Tailwind CSS for styling.

1. Project Setup

Start by creating a new Node.js project. Initialize a new project using:

npm init -y

Install the required dependencies:

npm install express ejs tailwindcss

2. Setting Up Express with EJS

Create a basic Express application and configure EJS as the view engine. Let’s assume your main application file is app.js:

File Structure

your-nodejs-website/
|-- node_modules/
|-- public/
|   |-- styles/
|       |-- main.css
|       |-- tailwind.css
|-- views/
|   |-- index.ejs
|-- app.js
|-- package.json
|-- package-lock.json
|-- tailwind.config.js

app.js

const express = require('express');
const ejs = require('ejs');
const app = express();

app.set('view engine', 'ejs');
app.use(express.static('public'));

app.get('/', (req, res) => {
  res.render('index');
});

app.listen(3000, () => {
  console.log(`Server running at http://localhost:3000/`);
});

3. Configuring Tailwind CSS

Create a tailwind.css file for your custom styles. Add the following content:

public/styles/tailwind.css

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

In your package.json, add scripts for compiling Tailwind CSS. Modify the “scripts” section:

package.json

"scripts": {
  "build:css": "tailwindcss build public/styles/tailwind.css -o public/styles/main.css"
}

Run the following command to initialize your Tailwind CSS configuration:

npx tailwindcss init

4. Creating EJS Views

Create a folder called views in your project directory. Inside the views folder, create an index.ejs file:

views/index.ejs

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="/styles/main.css">
  <title>Simple Website with EJS and Tailwind CSS</title>
</head>
<body class="bg-gray-200">
  <div class="container mx-auto my-8">
    <h1 class="text-4xl font-bold mb-4">Welcome to our Simple Website!</h1>
    <p class="text-lg">This is a basic website built with EJS and Tailwind CSS.</p>
  </div>
</body>
</html>

5. Building and Running the Project

Now, build your Tailwind CSS styles by running:

npm run build:css

Run your Express application:

node app.js

Visit http://localhost:3000 in your web browser to see the simple website.

Congratulations! You’ve created a basic website using EJS for templating and Tailwind CSS for styling. Feel free to expand and customize the content and styles to suit your needs. Happy coding!