🔧 How to Generate a Static Site Using Remix Run Framework SSG
Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to
Remix Run is a modern, full-stack web framework that enables developers to build robust web applications with excellent performance. It’s designed to manage both client and server-side logic, focusing heavily on performance and SEO. While Remix is typically used for dynamic, data-driven applications, it also excels in building static pages with ease. In this guide, we'll explore how to create static pages using the Remix Run framework.
What is a Static Page?
A static page is a web page whose content doesn't change based on user interactions or external data. Once a static page is built, it remains the same for all users until you update it manually. Static pages are ideal for things like landing pages, blogs, and documentation sites, where the content remains relatively constant over time.
Prerequisites
Before we dive in, ensure that you have the following:
- Node.js: Remix requires Node.js installed on your system.
- Remix: If you haven’t already, you can install the Remix CLI using:
npx create-remix@latest
Setting Up a Remix Project
First, you need to set up a Remix project. This can be done using the following command:
npx create-remix@latest remix-ssg
You will be prompted with some configuration options (such as deployment targets), but for static pages, the most common choice would be to use a simple "Remix App Server" or choose a "Deploy on Netlify" target for static site generation.
After the installation is complete, navigate to your new project:
cd remix-ssg
npm install
Project Structure Overview
Once you have the project set up, the folder structure will look something like this:
remix-ssg
├── app
│ ├── routes
│ │ └── _index.tsx
│ ├── entry.client.tsx
│ ├── entry.server.tsx
│ ├── tailwind.css
│ └── root.tsx
├── public
├── vite.config.js
└── package.json
The main folder of interest is the app/routes
folder. This is where Remix looks for files to create routes (or pages). Each file in the routes
folder corresponds to a route in the application.
Creating a Application Pages
To create a static page in Remix, you can create a new file in the routes
directory. For example, let’s create a static "About Us" page.
- Create a new file
about.tsx
inside theapp/routes
directory:
app/routes/about.tsx
- Add the following content to the file:
import { MetaFunction } from "@remix-run/react";
// Meta tags for SEO
export const meta: MetaFunction = () => {
return [
{ title: "About Us - Remix SSG Example" },
{ name: "description", content: "Welcome to Remix SSG App Example!" },
];
};
export default function AboutPage() {
return (
<div>
<h1>About Us</h1>
<p>This page was build by Remix Run as a static page</p>
</div>
);
}
That’s it! This simple setup is enough to create a static "About Us" page.
Handling Links in SSG
After creating the pages that we want to build statically. Now we need to Link these pages by using: <Link reloadDocument to={'/about'}>
or <a href={'/about'}>
to do a full page reload when switching between the pages.
Generate Site Pages
The main purpose of generating static pages is to pre-render them as HTML files at build time by running a server locally. These pages are then saved and can be served directly from storage, eliminating the need for server processing (CPU) during runtime.
First Step we need to build the app by running npm run build
This will create a new folder called build
remix-ssg
├── app
├── build
│ ├── client
│ └── server
├── public
├── vite.config.js
└── package.json
Now we need to run the app and get our HTML pages and save them in build/client
folder
To run the app we need to run npm run start
command in terminal and we can see our app running on port 3000
(http://localhost:3000/) Now we need to visit all the routes and save the html content. To do so we can need to add the following file:
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import wget from "wget-improved";
import waitPort from "wait-port";
const __filename = fileURLToPath(import.meta.url); // get the resolved path to the file
const __dirname = path.dirname(__filename); // get the name of the directory
const baseURL = `http://localhost:3000`;
const outputPath = `build/client`;
function saveFile(fileName) {
let fullURL = `${baseURL}/${fileName}`;
let outputFileName = `${outputPath}/${fileName}`;
if (fullURL.endsWith("/")) {
outputFileName = `${outputFileName}index`;
}
let download = wget.download(fullURL, `${outputFileName}.html`);
download.on("end", function () {
console.log(`Page ${fileName} build successfully`);
});
download.on("error", function (err) {
console.log(err);
});
}
function getRouteFromFileName(fileName) {
let parts = fileName.split(".");
parts.pop();
return parts.join("/").replaceAll("_index", "");
}
await waitPort({
port: 3000,
host: "localhost",
});
const directoryPath = path.join(__dirname, "app", "routes");
let files = [];
try {
files = fs.readdirSync(directoryPath);
files.forEach((file) => {
const route = getRouteFromFileName(file);
saveFile(route);
});
} catch (error) {
console.error(error);
}
You can change the build command in package.json
to the following which will do everything
"build": "remix vite:build && concurrently --kill-others --success first \"node generate-files.js\" \"npm run start\""
And Now we have the build file and static pages ready to deploy
Deploying Your Static Pages
You can deploy your static Remix app using platforms like Netlify, Vercel, or even GitHub Pages. For static site generation (SSG) with Remix, the deployment platform will statically render your pages at build time.
For example, to deploy to Netlify:
- Install Netlify CLI:
npm install -g netlify-cli
- Link your project to Netlify:
netlify init
- Deploy:
netlify deploy --build
Netlify will statically generate and deploy your Remix site!
Conclusion
In conclusion, generating static pages with the Remix Run framework is an efficient way to create fast, SEO-optimized websites. By pre-rendering pages at build time and serving them directly from storage, you eliminate the need for server-side processing, leading to faster load times and reduced server costs. Remix’s flexibility allows you to manage both static and dynamic content seamlessly. Whether you're deploying to platforms like Netlify, Vercel, or even GitHub Pages, Remix’s static site generation capabilities provide a powerful solution for building high-performance web applications.
Inspired By
This guide was inspired by insights shared in this post by Michael Jackson, co-creator of Remix. His thoughts on static site generation in Remix helped shape this article.
Source Code: https://github.com/HinnHabib/remix-ssg
Live Exmaple: https://remix-ssg.habibhinn.com
Original Link: https://habibhinn.com/blog/how-to-generate-a-static-site-using-remix-run-framework