mdsvex-enhanced-images
Version:
An MDsveX plugin to preprocess Markdown images using @sveltejs/enhanced-img.
114 lines (89 loc) • 3.08 kB
Markdown
This plugin converts Markdown images to `<enhanced:img>` components.
- Automatically imports images used in Markdown
- Converts Markdown image syntax to `<enhanced:img>`
- Skips HTTP/HTTPS URLs to avoid processing errors with external images
- Handles path resolution for various import scenarios
- Preserves title attributes from Markdown images
```bash
npm install mdsvex mdsvex-enhanced-images @sveltejs/enhanced-img
```
```js
// svelte.config.js
import { enhancedImages } from 'mdsvex-enhanced-images'
export default {
preprocess: [
mdsvex({
remarkPlugins: [enhancedImages]
})
]
}
```
```js
// vite.config.js
import { enhancedImages } from '@sveltejs/enhanced-img'
import { sveltekit } from '@sveltejs/kit/vite'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [enhancedImages(), sveltekit()]
})
```
Now use normal Markdown-style images just as you normally would. By default, paths beginning with `$`, `@`, `./`, or `../` are left unchanged while all other paths are converted to relative paths by prepending `./`.
```md
 // Resolves to ./example.png
 // Resolves to ../example.png
 // Resolves to $images/example.png
 // Resolves to @images/example.png
// Title attributes are preserved

// External URLs remain as standard <img> tags

```
## Advanced Usage: Custom Path Resolution
If the default path resolution strategy doesn't work for your needs, you can optionally provide a custom `resolve` function:
```js
mdsvex({
remarkPlugins: [
[
enhancedImages,
{
resolve: (path) => path
}
]
]
})
```
If you just want to change the resolution of non-relative paths (most common case), you can use `defaultResolverFactory` to create a custom resolver. The factory's stock resolver will handle paths starting with `$`, `@`, or `./` or `../` unchanged, and call your custom relative resolver for all other paths.
```js
// svelte.config.js
import { defaultResolverFactory } from 'mdsvex-enhanced-images'
import { join } from 'path'
const config = {
preprocess: [
mdsvex({
remarkPlugins: [
[
enhancedImages,
{
resolve: defaultResolverFactory((path) =>
join('src', 'assets', 'images', path)
)
}
]
]
})
]
}
```
Now, images with non-relative paths in Markdown will resolve to `src/assets/images`:
```md
 // Resolves to src/assets/images/example.png (new)
 // Resolves to ../example.png (unchanged)
 // Resolves to $images/example.png (unchanged)
 // Resolves to @images/example.png (unchanged)
```
MIT