1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2025-11-05 08:45:41 -05:00

add a *very* basic minifier to remove the insane amount of whitespace from compiled MDX

This commit is contained in:
2024-02-28 14:59:01 -05:00
parent 1c1f2ef9e9
commit e661ca48b8
4 changed files with 64 additions and 24 deletions

25
lib/helpers/minifier.ts Normal file
View File

@@ -0,0 +1,25 @@
import { trimLines } from "trim-lines";
import stripComments from "strip-comments";
// do some _very_ rudimentary JS minifying.
export const minifier = (source: string): string => {
// save the first line for later, it might be important?
const firstLine = source.split("\n")[0];
// remove JS comments
source = stripComments(source, {
block: false,
keepProtected: true,
});
// remove indentation
source = trimLines(source);
// remove newlines
source = source.replace(/\n/g, "");
// restore JSX flags if they were there at the beginning
if (firstLine.startsWith("/*@jsx")) {
source = `${firstLine}${source}`;
}
return source;
};

View File

@@ -6,6 +6,7 @@ import pMap from "p-map";
import pMemoize from "p-memoize";
import matter from "gray-matter";
import { formatDate } from "./format-date";
import { minifier } from "./minifier";
import type { PostFrontMatter, PostWithSource } from "../../types";
// path to directory with .mdx files, relative to project root
@@ -18,15 +19,15 @@ export const getPostData = async (
frontMatter: PostFrontMatter;
markdown: string;
}> => {
const fullPath = path.join(process.cwd(), POSTS_DIR, `${slug}.mdx`);
const rawContent = await fs.readFile(fullPath, "utf8");
const { data, content } = matter(rawContent);
const { unified } = await import("unified");
const { remarkParse, remarkSmartypants, remarkRehype, rehypeSanitize, rehypeStringify } = await import(
"./remark-rehype-plugins"
);
const fullPath = path.join(process.cwd(), POSTS_DIR, `${slug}.mdx`);
const rawContent = await fs.readFile(fullPath, "utf8");
const { data, content } = matter(rawContent);
// allow *very* limited markdown to be used in post titles
const parseTitle = async (title: string, allowedTags: string[] = []): Promise<string> => {
return String(
@@ -68,12 +69,12 @@ export const getPostData = async (
// fully parses MDX into JS and returns *everything* about a post
export const compilePost = async (slug: string): Promise<PostWithSource> => {
const { frontMatter, markdown } = await getPostData(slug);
const { remarkGfm, remarkSmartypants, remarkUnwrapImages, rehypeSlug, rehypePrism } = await import(
"./remark-rehype-plugins"
);
const { frontMatter, markdown } = await getPostData(slug);
const { compiledSource } = await serialize(markdown, {
parseFrontmatter: false,
mdxOptions: {
@@ -105,7 +106,8 @@ export const compilePost = async (slug: string): Promise<PostWithSource> => {
return {
frontMatter,
source: {
compiledSource,
// save some bytes
compiledSource: minifier(compiledSource),
},
};
};