Build a JavaScript Single Page App Without a Framework

Front-end frameworks are great. They abstract away much of the complexity of building a single-page application (SPA) and help you organize your code in an intelligible manner as your project grows.
However, there’s a flip side: these frameworks come with a degree overhead and can introduce complexity of their own.
That’s why, in this tutorial, we’re going to learn how to build an SPA from scratch, without using a client-side JavaScript framework. This will help you evaluate what these frameworks actually do for you and at what point it makes sense to use one. It will also give you an understanding of the pieces that make up a typical SPA and how they’re wired together.
Let’s get started …
Prerequisites
For this tutorial, you’ll need a fundamental knowledge of modern JavaScript and jQuery. Some experience using Handlebars, Express and Axios will come handy, though it’s not strictly necessary. You’ll also need to have the following setup in your environment:

Node.js
Git or Git Bash for Window users.

You can find the completed project on our GitHub repository.
Building the Project
We’re going to build a simple currency application that will provide the following features:

display the latest currency rates
convert from one currency to another
display past currency rates based on a specified date.

We’ll make use of the following free online REST APIs to implement these features:

fixer.io API
Free Currency Converter API.

Fixer is a well-built API that provides a foreign exchange and currency conversion JSON API. Unfortunately, it’s a commercial service and the free plan doesn’t allow currency conversion. So we’ll also need to use the Free Currency Converter API. The conversion API has a few limitations, which luckily won’t affect the functionality of our application. It can be accessed directly without requiring an API key. However, Fixer requires an API key to perform any request. Simply sign up on their website to get an access key for the free plan.
Ideally, we should be able to build the entire single-page application on the client side. However, since we’ll be dealing with sensitive information (our API key) it won’t be possible to store this in our client code. Doing so will leave our app vulnerable and open to any junior hacker to bypass the app and access data directly from our API endpoints. To protect such sensitive information, we need to put it in server code. So, we’ll set up an Express server to act as a proxy between the client code and the cloud services. By using a proxy, we can safely access this key, since server code is never exposed to the browser. Below is a diagram illustrating how our completed project will work.

Take note of the npm packages that will be used by each environment — i.e. browser (client) and server. Now that you know what we’ll be building, head over to the next section to start creating the project.
Project Directories and Dependencies
Head over to your workspace directory and create the folder single-page-application. Open the folder in VSCode or your favorite editor and create the following files and folders using the terminal:
touch .env .gitignore README.md server.js
mkdir public lib
mkdir public/js
touch public/index.html
touch public/js/app.js

Open .gitignore and add these lines:
node_modules
.env

Open README.md and add these lines:
# Single Page Application

This is a project demo that uses Vanilla JS to build a Single Page Application.

Next, create the package.json file by executing the following command inside the terminal:
npm init -y

You should get the following content generated for you:
{
“name": "single-page-application",
"version": "1.0.0",
"description": "This is a project demo that uses Vanilla JS to build a Single Page Application.",
"main": "server.js",
"directories": {
"lib": "lib"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}

See how convenient the npm command is? The content has been generated based on the project structure. Let’s now install the core dependencies needed by our project. Execute the following command in your terminal:
npm install jquery semantic-ui-css handlebars vanilla-router express dotenv axios

After the packages have finished installing, head over to the next section to start building the base of the application.
Application Base
Before we start writing our front-end code, we need to implement a server–client base to work from. That means a basic HTML view being served from an Express server. For performance and reliability reasons, we’ll inject front-end dependencies straight from the node_modules folder. We’ll have to set up our Express server in a special way to make this work. Open server.js and add the following:
require(‘dotenv’).config(); // read .env files
const express = require(‘express’);

const app = express();
const port = process.env.PORT || 3000;

// Set public folder as root
app.use(express.static(‘public’));

// Allow front-end access to node_modules folder
app.use(‘/scripts’, express.static(`${__dirname}/node_modules/`));

// Listen for HTTP requests on port 3000
app.listen(port, () => {
console.log(‘listening on %d’, port);
});

This gives us a basic Express server. I’ve commented the code, so hopefully this gives you a fairly good idea of what’s going on. Next, open public/index.html and enter:

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="scripts/semantic-ui-css/semantic.min.css">
<title>SPA Demo</title>
</head>
<body>
<div class="ui container">
<!– Navigation Menu –>
<div class="ui four item inverted orange menu">
<div class="header item">
<i class="money bill alternate outline icon"></i>
Single Page App
</div>
<a class="item" href="/">
Currency Rates
</a>
<a class="item" href="/exchange">
Exchange Rates
</a>
<a class="item" href="/historical">
Historical Rates
</a>
</div>

<!– Application Root –>
<div id="app"></div>
</div>

<!– JS Library Dependencies –>
<script src="scripts/jquery/dist/jquery.min.js"></script>
<script src="scripts/semantic-ui-css/semantic.min.js"></script>
<script src="scripts/axios/dist/axios.min.js"></script>
<script src="scripts/handlebars/dist/handlebars.min.js"></script>
<script src="scripts/vanilla-router/dist/vanilla-router.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>

We’re using Semantic UI for styling. Please refer to the Semantic UI Menu documentation to understand the code used for our navigation bar. Go to your terminal and start the server:
npm start

Open localhost:3000 in your browser. You should have a blank page with only the navigation bar showing:

Let’s now write some view templates for our app.
Front-end Skeleton Templates
We’ll use Handlebars to write our templates. JavaScript will be used to render the templates based on the current URL. The first template we’ll create will be for displaying error messages such as 404 or server errors. Place this code in public/index.html right after the the navigation section:
<!– Error Template –>
<script id="error-template" type="text/x-handlebars-template">
<div class="ui inverted segment" style="height:250px;">
<br>
<h2 class="ui center aligned icon header">
<i class="exclamation triangle icon"></i>
<div class="content">
Build a JavaScript Single Page App Without a Framework
<div class="sub header"></div>
</div>
</h2>
</div>
</script>

Next, add the following templates that will represent a view for each URL path we specified in the navigation bar:
<!– Currency Rates Template –>
<script id="rates-template" type="text/x-handlebars-template">
<h1 class="ui header">Currency Rates</h1>
<hr>
</script>

<!– Exchange Conversion Template –>
<script id="exchange-template" type="text/x-handlebars-template">
<h1 class="ui header">Exchange Conversion</h1>
<hr>
</script>

<!– Historical Rates Template –>
<script id="historical-template" type="text/x-handlebars-template">
<h1 class="ui header">Historical Rates</h1>
<hr>
</script>

Next, let’s compile all theses templates in public/js/app.js. After compilation, we’ll render the rates-template and see what it looks like:
window.addEventListener(‘load’, () => {
const el = $(‘#app’);

// Compile Handlebar Templates
const errorTemplate = Handlebars.compile($(‘#error-template’).html());
const ratesTemplate = Handlebars.compile($(‘#rates-template’).html());
const exchangeTemplate = Handlebars.compile($(‘#exchange-template’).html());
const historicalTemplate = Handlebars.compile($(‘#historical-template’).html());

const html = ratesTemplate();
el.html(html);
});

Take note that we’re wrapping all JavaScript client code inside a load event. This is just to make sure that all dependencies have been loaded and that the DOM has completed loading. Refresh the page and see what we have:

We’re making progress. Now, if you click the other links, except Currency Rates, the browser will try to fetch a new page and end up with a message like this: Cannot GET /exchange.
We’re a building a single page application, which means all the action should happen in one page. We need a way to tell the browser to stop fetching new pages whenever the URL changes.
The post Build a JavaScript Single Page App Without a Framework appeared first on SitePoint.

Link: https://www.sitepoint.com/single-page-app-without-framework/