Skip to content

Support relative imports of MDX assets #266

Closed
@gergelypap

Description

@gergelypap

It is a really common requirement to have subdirectories for each and every MDX content, where different assets, such as images and components can be coupled.

Example file structure:

data
├── post-01
│   ├── Component.tsx
│   ├── image.jpg
│   └── index.mdx
└── post-02
    ├── Component.tsx
    ├── image.jpg
    └── index.mdx

It is possible to configure contentlayer to load the MDX files in this manner, however it is not currently possible to allow for relative imports of assets, such that:

---
title: My post
---

import Component from './Component';

<Component />

![Image](./image.jpg)

(Image loading is discussed in #11 though.)

UPDATE:

Upon investigating, I found that the cwd given to mdx-bundler is the same as contentDirPath. However, if the MDX file is deeply nested, resolving images and components in the same directory will not work. For example if contentDirPath is /content, but the MDX file is under /content/some-subdir/some-post/index.mdx, any references in the MDX file will be looked in /content.

More precisely: if the MDX file references ![](./image.jpg) or import Component from './Component, those files will try to be resolved from /content, and not /content/some-subdir/some-post where they actually are.

https://github.com/contentlayerdev/contentlayer/blob/main/packages/%40contentlayer/core/src/markdown/mdx.ts#L45 -> should really be: cwd: path.join(cwd, rawDocumentData.flattenedPath).

This simple change solved this issue for me. I will make more tests and perhaps submit a PR on this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions