Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hagevvashi/d861cc4f103fa56e9bfccd425e702c62 to your computer and use it in GitHub Desktop.
Save hagevvashi/d861cc4f103fa56e9bfccd425e702c62 to your computer and use it in GitHub Desktop.
html-webpack-pluginのtemplateの実装
import type HtmlWebpackPlugin from "html-webpack-plugin";
import React, { FC, ReactElement } from "react";
import { renderToString } from "react-dom/server";
import { ServerStyleSheet, createGlobalStyle } from "styled-components";
function route(action: string): ReactElement {
switch (action) {
case "page1": {
return <Page1 />;
}
case "page2": {
return <Page2 />;
}
default: {
throw new Error("ありえない chunks が設定されているのでエラー");
}
}
}
function validateChunks(
chunks: HtmlWebpackPlugin.TemplateParameter["htmlWebpackPlugin"]["options"]["chunks"]
): asserts chunks is [string] {
if (!chunks) {
throw new Error("chunks というパラメータがないのは想定外なのでエラー");
}
if (chunks === "all") {
throw new Error('chunks が "all" になっているのは想定外なのでエラー');
}
if (chunks.length !== 1) {
throw new Error("chunks の要素が 1 つじゃないのは想定外なのでエラー");
}
}
export default ({
htmlWebpackPlugin: {
options: { chunks },
},
}: HtmlWebpackPlugin.TemplateParameter): string => {
validateChunks(chunks);
const [action] = chunks;
const sheet = new ServerStyleSheet();
const reactDom = renderToString(sheet.collectStyles(route(action)));
const styleTags = sheet.getStyleTags();
return templateHtml(action, reactDom, styleTags);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment