astro的md配置本地图片加载

astro的md配置本地图片加载

  1. code
  2. 4 months ago
  3. 2 min read

我写博客一般是在当前目录新建一个asstes目录,将图片放在里面,如果是<img>标签引入图片,上传到博客网站上,这种图片无法正常加载,于是写了个插件,将./asstes目录下的图片复制到public/images目录,然后自动替换md文件里img标签里的src属性。

插件代码如下

//imgproccer.ts
import { defineConfig } from 'astro/config';
import path from 'path';
import fs from 'fs/promises';
import { glob } from 'glob';
import type { AstroConfig } from 'astro';

export function imageProcessor() {
  return {
    name: 'image-processor',
    hooks: {
      'astro:config:setup': async ({ config }: { config: AstroConfig }) => {
        console.log('Image processor starting...');
        
        const rootDir = typeof config.root === 'string' ? config.root : config.root.pathname;
        const contentDir = path.join(rootDir, 'src', 'content');
        const publicDir = path.join(rootDir, 'public');
        const imageDir = path.join(publicDir, 'images');
        console.log('publicDir', publicDir);
        console.log('Content directory:', contentDir);
        console.log('Public directory:', publicDir);
        console.log('Image directory:', imageDir);

        await fs.mkdir(imageDir, { recursive: true });
        console.log('Image directory created or already exists');

        console.log('Processing Markdown files...');
        const mdFiles = await glob('**/*.md', { cwd: contentDir });
        for (const mdFile of mdFiles) {
            console.log("mdFile", mdFile);
            const filePath = path.join(contentDir, mdFile);
            let content = await fs.readFile(filePath, 'utf-8');
            const imgRegex = /<img\s+src=["'](.+?)["']/g;
            let match;
            while ((match = imgRegex.exec(content))) {
            //只要以./assets开头的
            if (match[1].startsWith('./assets')) {
                const src = match[1];
                //获取完整路径
                const fullPath = path.join(contentDir, mdFile,"../",src);
                console.log("src", src);
                console.log("fullPath", fullPath);
                const destPath = path.join(imageDir, mdFile,"../",src);
                console.log("destPath", destPath);
                await fs.mkdir(path.dirname(destPath), { recursive: true });
                await fs.copyFile(fullPath, destPath);
                //替换img标签里的src为newSrc
                const newSrc = `/images/${path.relative(contentDir, fullPath)}`;
                console.log("newSrc", newSrc);
                content = content.replace(`<img src="${src}"`, `<img src="${newSrc}"`);
                console.log(`Replaced ${src} with ${newSrc}`);
                await fs.writeFile(filePath, content);

            }

在astro.config.mjs中引入

import { imageProcessor } from './src/support/imgproccer.ts'

export default defineConfig({
   ....
    integrations: [
    .....
        imageProcessor(),
     ......
    ],

由于默认astro的markdown图片不能居中,还在layouts里面加入了如下配置让图片居中显示

............
            /* 图片居中显示 */
            :global(img) {
                @apply mx-auto;
            }
        </style>
    </body>
</html>
code 配置 astro markdown