Diterbitkan pada

Vanila Halaman tunggal

Penulis
  • avatar
    Nama
    Naufal Akbar Nugroho
Table of Contents

Ini adalah cara saya membuat satu halaman hanya dengan HTML, SCSS, dan Vanila JavaScript.

Prosedur

  1. Sebelum memulai proyek, pastikan Anda sudah memiliki node.js di komputer Anda. Jika Anda tidak memilikinya, unduh di sini.
  2. Buat folder dengan nama apapun yang Anda inginkan.
  3. Masuk ke folder yang telah Anda buat dan masukkan editor teks favorit Anda.
  4. Buat file HTML dengan nama index.html. Berikut sintaksnya.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vanilla Single Page</title>
    <link rel="stylesheet" href="static/scss/index.css" type="text/css" />
</head>
<body>
    <!-- This is navigation -->
    <nav class="nav">
    <a href="/vanilla-singlepage/" class="nav__link" data-link>Dashboard</a>
    <a href="/vanilla-singlepage/posts" class="nav__link" data-link>Posts</a>
    <a href="/vanilla-singlepage/settings" class="nav__link" data-link>Settings</a>
    </nav>
    <!-- This is end navigation -->

    <!-- These are all the components we created and render in here -->
    <div id="app"></div>

    <!-- This is where we load the package -->
    <script type="module" src="static/js/index.js"></script>
</body>
</html>
  1. Kemudian jalankan sintaks npm.
cmd
    $ npm init -y

atau

cmd
   $ yarn init -y
  1. Kemudian instal modul express.
cmd
    $ npm install express

atau

cmd
    $ yarn add express
  1. Kemudian buat file dengan nama server.js. Berikut sintaksnya.
server.js
const express = require("express"); // this is where we load the package
const path = require("path"); // this is where we load the path url

const app = express(); // we initialize the package

app.use("/static", express.static(path.resolve(__dirname, "frontend", "static"))); // locate the folder page

app.get("/*", (req, res) => {
res.sendFile(path.resolve(__dirname, "frontend", "index.html"));
}); // create path url

app.listen(process.env.PORT || 4040, () => console.log("Server running...")); // the port where the server run
  1. Jalankan server dengan sintaks berikut.
cmd
    $ node server.js
  1. Kemudian buka browser Anda dan kunjungi tautan http://localhost:4040.
  2. Kemudian buat folder dengan nama static dan di dalamnya terdapat 2 folder yaitu folder js dan scss
  3. Kemudian buat folder dengan nama view. di folder tampilan, buat halaman yang Anda inginkan. dalam kasus saya, saya membuat Dasboard.js, FormatView.js, PostView.js, Posts.js, Settings.js.
static/js/view/FormatView.js
export default class {
    constructor(params) {
        this.params = params;
    }

    setTitle(title) {
        document.title = title;
    }

    async getHtml() {
        return "";
    }
}
static/js/view/Dashboard.js
import FormatView from "./FormatView.js";

export default class extends FormatView {
    constructor(params) {
        super(params);
        this.setTitle("Dashboard | Vanilla Single Page - Naufal Akbar Nugroho");
    }

    async getHtml() {
        return `
                <h1>Hai, Nopal</h1>
                <p>
                    Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum earum culpa molestias itaque repudiandae hic laboriosam atque cupiditate? Molestiae nemo fugiat illo error corporis, recusandae et ipsum! Animi, soluta harum.
                </p>
                <p>
                    <a href="/vanilla-singlepage/posts" data-link>View recent posts</a>.
                </p>
            `;
    }
}
static/js/view/PostView.js
import FormatView from "./FormatView.js";

export default class extends FormatView {
    constructor(params) {
        super(params);
        this.postId = params.id;
        this.setTitle("Viewing Post | Vanilla Single Page - Naufal Akbar Nugroho");
    }

    async getHtml() {
        return `
                <h1>Post</h1>
                <p>You are viewing post #${this.postId}.</p>
            `;
    }
}
static/js/view/Posts.js
import FormatView from "./FormatView.js";

export default class extends FormatView {
    constructor(params) {
        super(params);
        this.setTitle("Posts | Vanilla Single Page - Naufal Akbar Nugroho");
    }

    async getHtml() {
        return `
                <h1>Posts</h1>
                <p>You are viewing the posts!</p>
            `;
    }
}
static/js/view/Settings.js
import FormatView from "./FormatView.js";

export default class extends FormatView {
    constructor(params) {
        super(params);
        this.setTitle("Settings | Vanilla Single Page - Naufal Akbar Nugroho");
    }

    async getHtml() {
        return `
                <h1>Settings</h1>
                <p>Manage your privacy and configuration.</p>
            `;
    }
}
  1. Kemudian buat file dengan nama index.js dan berikut sintaksnya.
static/js/index.js
import Dashboard from "./view/Dashboard.js";
import Posts from "./view/Posts.js";
import PostView from "./view/PostView.js";
import Settings from "./view/Settings.js";

const pathToRegex = (path) => new RegExp("^" + path.replace(/\//g, "\\/").replace(/:\w+/g, "(.+)") + "$");

const getParams = (match) => {
  const values = match.result.slice(1);
  const keys = Array.from(match.route.path.matchAll(/:(\w+)/g)).map((result) => result[1]);

  return Object.fromEntries(
    keys.map((key, i) => {
      return [key, values[i]];
    })
  );
};

const navigateTo = (url) => {
  history.pushState(null, null, url);
  router();
};

const router = async () => {
  const routes = [
    { path: "/vanilla-singlepage/", view: Dashboard },
    { path: "/vanilla-singlepage/posts", view: Posts },
    { path: "/vanilla-singlepage/posts/:id", view: PostView },
    { path: "/vanilla-singlepage/settings", view: Settings },
  ];

  // Test each route for potential match
  const potentialMatches = routes.map((route) => {
    return {
      route: route,
      result: location.pathname.match(pathToRegex(route.path)),
    };
  });

  let match = potentialMatches.find((potentialMatch) => potentialMatch.result !== null);

  if (!match) {
    match = {
      route: routes[0],
      result: [location.pathname],
    };
  }

  const view = new match.route.view(getParams(match));

  document.querySelector("#app").innerHTML = await view.getHtml();
};

window.addEventListener("popstate", router);

document.addEventListener("DOMContentLoaded", () => {
  document.body.addEventListener("click", (e) => {
    if (e.target.matches("[data-link]")) {
      e.preventDefault();
      navigateTo(e.target.href);
    }
  });

  router();
});
  1. Kemudian saat yang kita tunggu-tunggu, kita membuat stlying untuk halaman yang telah kita buat.
static/scss/index.scss
body {
  --nav-width: 200px;
  margin: 0 0 0 var(--nav-width);
  font-family: "Quicksand", sans-serif;
  font-size: 18px;
  background: #111827;
}

.nav {
  position: fixed;
  top: 0;
  left: 0;
  width: var(--nav-width);
  height: 100vh;
  background: #1e40af;
}

.nav__link {
  display: block;
  padding: 12px 18px;
  text-decoration: none;
  color: #eeeeee;
  font-weight: 500;
}

.nav__link:hover {
  background: rgba(255, 255, 255, 0.05);
}

#app {
  margin: 2em;
  line-height: 1.5;
  font-weight: 500;
}

a {
  color: #4b80c4;
}
  1. Jadi kita memiliki Vanila Halaman Tunggal kita menggunakan HTML, SCSS, dan Vanila JavaScript!

Situs demo

Menyelesaikan

Selamat! Anda telah menyelesaikan tutorial cara membuat Vanila Halaman Tunggal menggunakan HTML, SCSS, Vanila Javascript! Semoga cuplikan kode ini dapat memberi manfaat untuk kalian semua dan jangan lupa untuk membagikan cuplikan kode ini kepada semua orang! Terima kasih!

Ikuti Saya!

Github Instagram X Linkedin Email