Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make PWA if manifest.json is available #36

Merged
merged 9 commits into from
Jan 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions bin/ignite.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#!/usr/bin/env node
require("dotenv").config();

const fs = require("fs");
const path = require("path");
const glob = require("fast-glob");
const { app } = require("command-line-application");
const { createServer } = require("http");
const { parse } = require("url");
Expand All @@ -15,6 +17,7 @@ const { getTopLevelSections } = require("../dist/cjs/utils/docs-data");
const { buildSearchIndex } = require("../dist/cjs/utils/build-search-index");
const { buildRssFeed, test } = require("../dist/cjs/utils/build-rss-feed");
const { purgeUnusedCss } = require("../dist/cjs/utils/purge-unused-css");
const { generatePwaAssets } = require("../dist/cjs/utils/generate-pwa-assets");

const buildNext = require("next/dist/build").default;
const exportNext = require("next/dist/export").default;
Expand Down Expand Up @@ -92,26 +95,44 @@ if (args._command === "dev") {
}

console.log(`> Ready on http://localhost:3000/${sections[0]}`);
buildSearchIndex('public');
buildSearchIndex("public");
});
});
}

if (args._command === "build") {
const docsDir = path.resolve(path.join(process.cwd(), "docs"));
const distDir = path.join(docsDir, ".next");
const outdir = path.join(docsDir, "out");

buildNext(docsDir, config)
.then(() => exportNext(docsDir, { outdir }))
.then(() => buildSearchIndex())
.then(() => {
.then(async () => {
console.log("Export successful", 0);
execSync(
`touch ${path.resolve(path.join(process.cwd(), "docs/out/.nojekyll"))}`
);
buildSitemap();
buildRssFeed(igniteConfig);
purgeUnusedCss(igniteConfig);

if (config.env.BUILD_PWA === "true") {
fs.copyFileSync(
path.join(distDir, "sw.js"),
path.join(outdir, "sw.js")
);
const workbox = glob.sync(path.join(distDir, "workbox-*.js"));

if (workbox[0]) {
fs.copyFileSync(
workbox[0],
path.join(outdir, path.basename(workbox[0]))
);
}

await generatePwaAssets(igniteConfig)
}
})
.catch((err) => {
console.error("");
Expand Down
43 changes: 43 additions & 0 deletions docs/pages/_document.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from "react";
import Document, { Html, Head, Main, NextScript } from "next/document";
import { formatPath } from "next-ignite";

class MyDocument extends Document {
render() {
Expand All @@ -15,6 +16,48 @@ class MyDocument extends Document {
href="https://www.unpkg.com/prism-themes@1.5.0/themes/prism-coldark-dark.css"
media="(prefers-color-scheme: dark)"
/>

<meta name="application-name" content="next-ignite Docs" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta
name="apple-mobile-web-app-status-bar-style"
content="default"
/>
<meta name="apple-mobile-web-app-title" content="next-ignite Docs" />
<meta
name="description"
content="The documentation for next-ignite"
/>
<meta name="format-detection" content="telephone=no" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="msapplication-TileColor" content="#11151d" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="theme-color" content="#11151d" />
<link rel="manifest" href={formatPath("/manifest.json")} />
<link rel="shortcut icon" href="/images/favicon.ico" />

<meta name="twitter:card" content="summary" />
<meta
name="twitter:url"
content="https://hipstersmoothie.github.io/next-ignite/"
/>
<meta name="twitter:title" content="next-ignite Docs" />
<meta
name="twitter:description"
content="The documentation for next-ignite"
/>
<meta name="twitter:creator" content="@hipstersmoothie" />
<meta property="og:type" content="website" />
<meta property="og:title" content="next-ignite Docs" />
<meta
property="og:description"
content="The documentation for next-ignite"
/>
<meta property="og:site_name" content="next-ignite Docs" />
<meta
property="og:url"
content="https://hipstersmoothie.github.io/next-ignite/"
/>
</Head>
<body>
<Main />
Expand Down
63 changes: 63 additions & 0 deletions docs/pages/docs/advanced-features/pwa.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
---
title: "Creating a Progressive Web App"
---

To make your `next-ignite` website into a PWA do the following:

1. Create a `docs/public/manifest.json`:

```json
{
"name": "next-ignite Docs",
"short_name": "ignite",
"icons": [
{
"src": "/public/logo.svg",
"sizes": "128x128",
"type": "image/png"
}
],
"theme_color": "#3b82f6",
"background_color": "#11151d",
"start_url": "/",
"display": "standalone",
"orientation": "portrait"
}
```

2. Fill out your `_document.js`'s `head`:

```html
<meta name='application-name' content='PWA App' />
<meta name='apple-mobile-web-app-capable' content='yes' />
<meta name='apple-mobile-web-app-status-bar-style' content='default' />
<meta name='apple-mobile-web-app-title' content='PWA App' />
<meta name='description' content='Best PWA App in the world' />
<meta name='format-detection' content='telephone=no' />
<meta name='mobile-web-app-capable' content='yes' />
<meta name='msapplication-config' content='/static/icons/browserconfig.xml' />
<meta name='msapplication-TileColor' content='#2B5797' />
<meta name='msapplication-tap-highlight' content='no' />
<meta name='theme-color' content='#000000' />

<link rel='apple-touch-icon' sizes='180x180' href='/static/icons/apple-touch-icon.png' />
<link rel='icon' type='image/png' sizes='32x32' href='/static/icons/favicon-32x32.png' />
<link rel='icon' type='image/png' sizes='16x16' href='/static/icons/favicon-16x16.png' />
<link rel='manifest' href='/static/manifest.json' />
<link rel='mask-icon' href='/static/icons/safari-pinned-tab.svg' color='#5bbad5' />
<link rel='shortcut icon' href='/static/icons/favicon.ico' />
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto:300,400,500' />

<meta name='twitter:card' content='summary' />
<meta name='twitter:url' content='https://yourdomain.com' />
<meta name='twitter:title' content='PWA App' />
<meta name='twitter:description' content='Best PWA App in the world' />
<meta name='twitter:image' content='https://yourdomain.com/static/icons/android-chrome-192x192.png' />
<meta name='twitter:creator' content='@DavidWShadow' />
<meta property='og:type' content='website' />
<meta property='og:title' content='PWA App' />
<meta property='og:description' content='Best PWA App in the world' />
<meta property='og:site_name' content='PWA App' />
<meta property='og:url' content='https://yourdomain.com' />
<meta property='og:image' content='https://yourdomain.com/static/icons/apple-touch-icon.png' />
```
16 changes: 16 additions & 0 deletions docs/public/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "next-ignite Docs",
"short_name": "ignite",
"icons": [
{
"src": "/next-ignite/logo.svg",
"sizes": "144x144",
"type": "image/png"
}
],
"theme_color": "#11151d",
"background_color": "#11151d",
"start_url": "/next-ignite/",
"display": "standalone",
"orientation": "portrait"
}
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,13 @@
"next": "^10.0.5",
"next-mdx-enhanced": "^4.0.0",
"next-prefixed": "^0.0.11",
"next-pwa": "^5.0.4",
"nextjs-sitemap-generator": "^1.0.0",
"parse-github-url": "^1.0.2",
"pretty-bytes": "^5.5.0",
"purgecss": "^3.1.3",
"push-dir": "^0.4.1",
"pwa-asset-generator": "^4.1.1",
"react": "16.13.0",
"react-dom": "16.13.0",
"react-merge-refs": "^1.1.0",
Expand Down
26 changes: 21 additions & 5 deletions src/next.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import autoLink from "rehype-autolink-headings";
import a11yEmoji from "rehype-accessible-emojis";
import slug from "rehype-slug";
import emoji from "remark-emoji";
import withPWA from "next-pwa";

import { getEnv } from "./utils/get-env";
import { IgniteConfig } from "./utils/types";
Expand All @@ -18,7 +19,10 @@ const withBundleAnalyzer = require("@next/bundle-analyzer")({
const getCreationDate = (file: string) => {
try {
return execSync(
`git log --diff-filter=A --follow --format=%aD -- ${path.join("docs/pages", file)} | tail -1`,
`git log --diff-filter=A --follow --format=%aD -- ${path.join(
"docs/pages",
file
)} | tail -1`,
{
encoding: "utf8",
stdio: ["pipe", "ignore", "ignore"],
Expand Down Expand Up @@ -70,8 +74,8 @@ const withMdxEnhanced = require("next-mdx-enhanced")({

if (!description && layout === "blog") {
const [, firstParagraph] =
mdx.match(/---\n\n^([^#].+?)(?=^$)/sm) ||
mdx.match(/\n\n^([^#].+?)(?=^$)/sm) ||
mdx.match(/---\n\n^([^#].+?)(?=^$)/ms) ||
mdx.match(/\n\n^([^#].+?)(?=^$)/ms) ||
[];

if (firstParagraph) {
Expand Down Expand Up @@ -111,7 +115,7 @@ module.exports = (igniteConfig: IgniteConfig = {}) => (nextConfig = {}) => {
...env,
};

return withBundleAnalyzer(
const config = withBundleAnalyzer(
withMdxEnhanced({
...nextConfig,
basePath,
Expand All @@ -120,8 +124,20 @@ module.exports = (igniteConfig: IgniteConfig = {}) => (nextConfig = {}) => {
},
env: {
...env,
browser: "true"
browser: "true",
},
})
);

if (env.BUILD_PWA === "true") {
return withPWA({
...config,
pwa: {
disable: process.env.NODE_ENV !== "production",
subdomainPrefix: env.BASE_PATH,
}
});
}

return config;
};
50 changes: 50 additions & 0 deletions src/utils/generate-pwa-assets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import * as pwaAssetGenerator from "pwa-asset-generator";
import path from "path";
import cheerio from "cheerio";
import glob from "fast-glob";
import fs from "fs";

import { DOCS_DIR } from "./docs-data";
import { getEnv } from "./get-env";
import { IgniteConfig } from "./types";

export const generatePwaAssets = async (config: IgniteConfig) => {
const env = getEnv(config);
const outDir = path.join(DOCS_DIR, "out");

console.log(env.BASE_PATH);

const light = await pwaAssetGenerator.generateImages(
path.join(DOCS_DIR, "public", env.PROJECT_LOGO),
outDir,
{ pathOverride: env.BASE_PATH, log: false }
);

// Add items to manifest

const manifestPath = path.join(outDir, "manifest.json");
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));

manifest.icons = [...light.manifestJsonContent];

fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));

// Add to html HEADs
const html = await glob(path.join(outDir, "**/*.html"));

html.map((file) => {
const $ = cheerio.load(fs.readFileSync(file, "utf-8"));
$("head").append(
Object.values(light.htmlMeta)
.map((image) => {
if (image.includes("apple-icon-180.jpg")) {
return image.replace("apple-icon-180.jpg", "apple-icon-180.png");
}

return image;
})
.join("\n")
);
fs.writeFileSync(file, $.html());
});
};
2 changes: 2 additions & 0 deletions src/utils/get-env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,14 @@ export const getEnv = (config: IgniteConfig) => {
: pathname.endsWith("/")
? pathname.slice(0, -1)
: pathname;
const manifest = glob.sync(path.join(publicDir, "**/manifest.json"))[0];
const favicon = glob.sync(path.join(publicDir, "**/favicon.*"))[0];
const faviconDark = glob.sync(path.join(publicDir, "**/favicon-dark.*"))[0];
const logo = glob.sync(path.join(publicDir, "**/logo.*"))[0];
const darkLogo = glob.sync(path.join(publicDir, "**/logo-dark.*"))[0];

return {
BUILD_PWA: String(Boolean(manifest)),
BASE_PATH: debug ? "/" : BASE_PATH || "/",
STATIC_HTML_URLS: debug
? ""
Expand Down
Loading