Skip to content

Commit

Permalink
fix: markdown cannot find relative image path without leading ./ (#10801
Browse files Browse the repository at this point in the history
)
  • Loading branch information
rishi-raj-jain committed Apr 23, 2024
1 parent 10c5b03 commit 204b782
Show file tree
Hide file tree
Showing 7 changed files with 33 additions and 9 deletions.
15 changes: 15 additions & 0 deletions .changeset/thirty-walls-yell.md
@@ -0,0 +1,15 @@
---
"astro": patch
---

Fixes an issue where images in MD required a relative specifier (e.g. `./`)

Now, you can use the standard `![](relative/img.png)` syntax in MD files for images colocated in the same folder: no relative specifier required!

There is no need to update your project; your existing images will still continue to work. However, you may wish to remove any relative specifiers from these MD images as they are no longer necessary:

```diff
- ![A cute dog](./dog.jpg)
+ ![A cute dog](dog.jpg)
<!-- This dog lives in the same folder as my article! -->
```
7 changes: 2 additions & 5 deletions packages/astro/src/vite-plugin-markdown/images.ts
@@ -1,13 +1,10 @@
export type MarkdownImagePath = { raw: string; resolved: string; safeName: string };
export type MarkdownImagePath = { raw: string; safeName: string };

export function getMarkdownCodeForImages(imagePaths: MarkdownImagePath[], html: string) {
return `
import { getImage } from "astro:assets";
${imagePaths
.map((entry) => {
const prefix = entry.raw.includes('/') ? '' : './';
return `import Astro__${entry.safeName} from ${JSON.stringify(prefix + entry.raw)};`;
})
.map((entry) => `import Astro__${entry.safeName} from ${JSON.stringify(entry.raw)};`)
.join('\n')}
const images = async function(html) {
Expand Down
10 changes: 7 additions & 3 deletions packages/astro/src/vite-plugin-markdown/index.ts
@@ -1,5 +1,4 @@
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import {
InvalidAstroDataError,
Expand Down Expand Up @@ -43,6 +42,13 @@ export default function markdown({ settings, logger }: AstroPluginOptions): Plug
buildEnd() {
processor = undefined;
},
async resolveId(source, importer, options) {
if (importer?.endsWith('.md') && source[0] !== '/') {
let resolved = await this.resolve(source, importer, options);
if (!resolved) resolved = await this.resolve('./' + source, importer, options);
return resolved;
}
},
// Why not the "transform" hook instead of "load" + readFile?
// A: Vite transforms all "import.meta.env" references to their values before
// passing to the transform hook. This lets us get the truly raw value
Expand Down Expand Up @@ -85,8 +91,6 @@ export default function markdown({ settings, logger }: AstroPluginOptions): Plug
for (const imagePath of rawImagePaths.values()) {
imagePaths.push({
raw: imagePath,
resolved:
(await this.resolve(imagePath, id))?.id ?? path.join(path.dirname(id), imagePath),
safeName: shorthash(imagePath),
});
}
Expand Down
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions packages/astro/test/fixtures/markdown/src/pages/images.md
@@ -0,0 +1,2 @@
![houston image](houston.png)
![nested houston image](relative/houston.png)
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 7 additions & 1 deletion packages/astro/test/markdown.test.js
Expand Up @@ -65,13 +65,19 @@ describe('Markdown tests', () => {
it('Can load a realworld markdown page with Astro', async () => {
const html = await fixture.readFile('/realworld/index.html');
const $ = cheerio.load(html);

assert.equal($('pre').length, 7);
});

it('Does not unescape entities', async () => {
const html = await fixture.readFile('/entities/index.html');
assert.match(html, /&#x3C;i>This should NOT be italic&#x3C;\/i>/);
});

it('Resolves the image paths correctly', async () => {
const html = await fixture.readFile('/images/index.html');
const $ = cheerio.load(html);
assert.equal($('img').first().attr('src').includes('.webp'), true);
assert.equal($('img').first().next().attr('src').includes('.webp'), true);
});
});
});

0 comments on commit 204b782

Please sign in to comment.