Skip to content

Commit db1dbbe

Browse files
committed
fix(marp): can not parse relative image path (#949)
1 parent 210a667 commit db1dbbe

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

plugin/custom/plugins/marp/index.js

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,38 @@ class marpPlugin extends BaseCustomPlugin {
4242
lazyLoad = () => {
4343
const { Marp } = require("./marp-core.min.js")
4444
this.Marp = Marp
45-
this.marp = new Marp(this.config.MARP_CORE_OPTIONS)
45+
this.marp = new Marp(this.config.MARP_CORE_OPTIONS).use(this._marpAbsoluteImagePath())
46+
}
47+
48+
_marpAbsoluteImagePath = () => {
49+
const toAbsPath = (url) => {
50+
const decodedURL = decodeURIComponent(url)
51+
const dir = this.utils.getCurrentDirPath()
52+
const absPath = (this.utils.isNetworkImage(decodedURL) || this.utils.isSpecialImage(decodedURL))
53+
? decodedURL
54+
: this.utils.Package.Path.resolve(dir, decodedURL)
55+
return absPath.split(this.utils.Package.Path.sep).join("/")
56+
}
57+
58+
return function (marp) {
59+
// Image commands (`![bg](...) `): They will be processed by `marp.normalizeLink`, replaced to the `background-image: url(...)` in `style` attribute.
60+
const originalNormalizeLink = marp.normalizeLink
61+
marp.normalizeLink = (url) => {
62+
const normalized = originalNormalizeLink(url)
63+
return toAbsPath(normalized)
64+
}
65+
const originalImageRule = marp.renderer.rules.image
66+
67+
// Ordinary images (`![alt](...) `): They will be processed by `md.renderer.rules.images`, replaced to the `src` attribute of the `<img>` tag.
68+
marp.renderer.rules.image = (tokens, idx, options, env, self) => {
69+
const token = tokens[idx]
70+
const srcIndex = token.attrIndex("src")
71+
if (srcIndex >= 0) {
72+
token.attrs[srcIndex][1] = toAbsPath(token.attrs[srcIndex][1])
73+
}
74+
return originalImageRule ? originalImageRule(tokens, idx, options, env, self) : self.renderToken(tokens, idx, options)
75+
}
76+
}
4677
}
4778
}
4879

0 commit comments

Comments
 (0)