kentcdodds / mdx-bundler

🦤 Give me MDX/TSX strings and I'll give you back a component you can render. Supports imports!
MIT License
1.78k stars 75 forks source link

Images not being copied to output directory in remix #185

Closed tconroy closed 2 years ago

tconroy commented 2 years ago

Hello!

I can't seem to get this to output images into my output directory. This is inside a remix project.

Relevant code or config

markdown file (image file is a sibling of content/hello-world/index.mdx):

---
slug: hello-world
title: Hello, world
date: 2022-06-30T18:11:21.183Z
---

testing

![](./hello-world.jpg 'Screenshot')

compile-mdx.server.ts - tried to truncate it to just the parts relevant to remark-mdx-images)

async function compileMdxImpl<FrontmatterType extends Record<string, unknown>>({
  slug,
  files,
}) {
  const [
    remarkMdxImages,
  ] = await Promise.all([
    import('remark-mdx-images').then(m => m.remarkMdxImages),
  ])

  const indexPattern = /index.mdx?$/
  const indexFile = files.find(({ path }) => path.match(indexPattern))
  if (!indexFile) {
    return null
  }

  const rootDir = indexFile.path.replace(indexPattern, '')
  const relativeFiles = files.map(({ path, content }) => ({
    path: path.replace(rootDir, './'),
    content,
  }))

  const filesObject = arrayToObject(relativeFiles, {
    keyname: 'path',
    valuename: 'content',
  })

  try {
    const { code, frontmatter } = await bundleMDX({
      source: indexFile.content,
      files: filesObject,
      mdxOptions: options => ({
        remarkPlugins: [
          ...(options.remarkPlugins ?? []),
          remarkMdxImages,
        ],
        rehypePlugins: [
          ...(options.rehypePlugins ?? []),
        ],
      }),
      esbuildOptions: options => {
        // Set the `outdir` to a public location for this bundle.
        options.outdir = path.resolve('public/build/_assets')

        options.loader = {
          ...options.loader,
          '.jpeg': 'file',
          '.jpg': 'file',
        }

        options.publicPath = path.join('/build/_assets')

        // Set write to true so that esbuild will output the files.
        options.write = true
        return options
      },
    })

    return {
      code,
      frontmatter: frontmatter as FrontmatterType,
    }
  } catch (e) {
    if (e instanceof Error) {
      console.log(e.message)
    }
    throw new Error(`MDX Compilation failed for ${slug}`)
  }
}

What you did:

What happened:

Other public assets (like favicon) are loading successfully (http://localhost:3000/build/_assets/twitter-32HBPWWL.svg)