@sctg/vite-plugin-github-pages-spa
Version:
Vite plugin to enable SPA (Single Page Application) support for GitHub Pages
146 lines (143 loc) • 5.04 kB
JavaScript
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
default: () => index_default,
githubPagesSpa: () => githubPagesSpa
});
module.exports = __toCommonJS(index_exports);
var import_node_path = require("path");
var import_node_fs = require("fs");
function githubPagesSpa(options = {}) {
const {
verbose = true,
injectScript = true,
custom404Html
} = options;
let config;
return {
name: "vite-plugin-github-pages-spa",
configResolved(resolvedConfig) {
config = resolvedConfig;
},
transformIndexHtml(html) {
const isGitHubPages = config.base.includes("github.io") || config.base !== "/";
if (!isGitHubPages || !injectScript) {
if (verbose && !isGitHubPages) {
console.warn("\nNot using GitHub Pages base URL. SPA redirection script not added.");
}
return html;
}
if (verbose) {
console.info("\nAdding GitHub Pages SPA redirection script to index.html");
}
return html.replace(
/<head>/,
`<head>
<script type="text/javascript">
// Single Page Apps Helper for GitHub Pages
// MIT License
// https://github.com/rafgraph/spa-github-pages
(function(l) {
if (l.search[1] === '/' ) {
var decoded = l.search.slice(1).split('&').map(function(s) {
return s.replace(/~and~/g, '&')
}).join('?');
window.history.replaceState(null, null,
l.pathname.slice(0, -1) + decoded + l.hash
);
}
}(window.location))
</script>`
);
},
closeBundle() {
const isGitHubPages = config.base.includes("github.io") || config.base !== "/";
if (!isGitHubPages) {
return;
}
const distPath = (0, import_node_path.resolve)(config.root, config.build.outDir);
if (!(0, import_node_fs.existsSync)(distPath)) {
(0, import_node_fs.mkdirSync)(distPath, { recursive: true });
}
const urlBase = new URL(config.base.startsWith("http") ? config.base : `http://example.com${config.base}`);
const urlPath = urlBase.pathname;
const pathSegmentsToKeep = urlPath.split("/").filter(Boolean).length;
let fileContent = custom404Html;
if (!fileContent) {
fileContent = `
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>404 - Page Not Found</title>
<script type="text/javascript">
// Single Page Apps for GitHub Pages
// MIT License
// https://github.com/rafgraph/spa-github-pages
var pathSegmentsToKeep = ${pathSegmentsToKeep}; // Number of path segments to keep in the URL
var l = window.location;
l.replace(
l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +
l.pathname.split('/').slice(0, 1 + pathSegmentsToKeep).join('/') + '/?/' +
l.pathname.slice(1).split('/').slice(pathSegmentsToKeep).join('/').replace(/&/g, '~and~') +
(l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') +
l.hash
);
</script>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
margin: 0;
padding: 20px;
text-align: center;
color: #333;
}
h1 {
margin-top: 50px;
font-size: 24px;
}
p {
margin: 20px 0;
font-size: 16px;
}
</style>
</head>
<body>
<h1>Page Not Found</h1>
<p>Redirecting to the home page...</p>
<p><a href="/">Click here if you are not redirected automatically</a></p>
</body>
</html>`;
}
const filePath = (0, import_node_path.resolve)(distPath, "404.html");
if (verbose) {
console.info(`
Creating 404.html in ${filePath} for GitHub Pages SPA support`);
}
(0, import_node_fs.writeFileSync)(filePath, fileContent);
}
};
}
var index_default = githubPagesSpa;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
githubPagesSpa
});