Skip to content

Commit

Permalink
Add remark plugin for copying images to public dir
Browse files Browse the repository at this point in the history
  • Loading branch information
marshallku committed Jan 16, 2025
1 parent 572ea46 commit b65f19f
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions apps/blog/src/constants/lib/post.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { join } from "path";

export const POSTS_DIRECTORY = join(process.cwd(), "_posts");
export const PUBLIC_DIRECTORY = join(process.cwd(), "public");

export const PAGE_SIZE = 9;
46 changes: 46 additions & 0 deletions apps/blog/src/plugins/lib/remarkLocalImages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { mkdirSync, copyFileSync } from "node:fs";
import { join, dirname, relative } from "node:path";
import { visit } from "unist-util-visit";
import { POSTS_DIRECTORY, PUBLIC_DIRECTORY } from "#constants";

export default function remarkLocalImages({ slug }: { slug: string }) {
const postsDir = POSTS_DIRECTORY;
const publicDir = PUBLIC_DIRECTORY;

return (tree: any, file: any) => {
visit(tree, "image", (node: any) => {
const imageUrl = node.url || "";
// Only handle local images (e.g., './images/foo.png')
if (!imageUrl.startsWith("./")) return;

// Absolute path to the MDX file
const mdxFilePath = join(postsDir, slug, "index.mdx");
// e.g. /Users/you/your-project/posts/hello-world/index.mdx
const mdxDir = dirname(mdxFilePath);

// Source image (on disk)
const sourcePath = join(mdxDir, imageUrl);
// e.g. /Users/you/your-project/posts/hello-world/images/sample.png

// Destination within publicDir
// -> We figure out a sub-directory by removing postsDir from sourcePath
// -> For example, if postsDir = /Users/you/your-project/posts
// subPath might be: hello-world/images/sample.png
const subPath = relative(postsDir, sourcePath);
// e.g. "hello-world/images/sample.png"

const targetPath = join(publicDir, "posts", subPath);
// e.g. /Users/you/your-project/public/posts/hello-world/images/sample.png

// Ensure the target directory exists
mkdirSync(dirname(targetPath), { recursive: true });

// Copy the image
copyFileSync(sourcePath, targetPath);

// Rewrite the Markdown image URL
// so that Next.js serves it from /posts/hello-world/images/sample.png
node.url = "/posts/" + subPath.replace(/\\/g, "/");
});
};
}

0 comments on commit b65f19f

Please sign in to comment.