diff --git a/packages/gatsby-plugin-mdx/package.json b/packages/gatsby-plugin-mdx/package.json index 981ca94aae495..4595f892f0276 100644 --- a/packages/gatsby-plugin-mdx/package.json +++ b/packages/gatsby-plugin-mdx/package.json @@ -42,6 +42,7 @@ "mdast-util-to-markdown": "^1.3.0", "mdast-util-toc": "^6.1.0", "rehype-infer-description-meta": "^1.0.1", + "remark-unwrap-images": "^3.0.1", "unified": "^10.1.2", "unist-util-visit": "^4.1.0", "vfile": "^5.3.2" diff --git a/packages/gatsby-plugin-mdx/src/plugin-options.ts b/packages/gatsby-plugin-mdx/src/plugin-options.ts index 32c031912c3b8..93f3386762dce 100644 --- a/packages/gatsby-plugin-mdx/src/plugin-options.ts +++ b/packages/gatsby-plugin-mdx/src/plugin-options.ts @@ -2,6 +2,7 @@ import type { ProcessorOptions } from "@mdx-js/mdx" import type { GatsbyCache, NodePluginArgs, PluginOptions, Store } from "gatsby" import deepmerge from "deepmerge" import type { IPluginInfo } from "gatsby-plugin-utils/types" +import { cachedImport } from "./cache-helpers" import { getSourcePluginsAsRemarkPlugins } from "./get-source-plugins-as-remark-plugins" import rehypeMdxMetadataExtractor from "./rehype-metadata-extractor" import { remarkMdxHtmlPlugin } from "./remark-mdx-html-plugin" @@ -51,6 +52,10 @@ export const enhanceMdxOptions: EnhanceMdxOptions = async ( ) => { const options = defaultOptions(pluginOptions) + const { default: remarkUnwrapImages } = await cachedImport< + typeof import("remark-unwrap-images") + >(`remark-unwrap-images`) + // Set jsxRuntime & jsxImportSource based on Gatsby project config const { config } = helpers.store.getState() const { jsxRuntime, jsxImportSource } = config @@ -61,6 +66,10 @@ export const enhanceMdxOptions: EnhanceMdxOptions = async ( options.mdxOptions.remarkPlugins = [] } + // The unwrapping has to happen before any other remark plugins are run (especially gatsby-remark-images) + // Otherwise remark-unwrap-images would operate on the already transformed images + options.mdxOptions.remarkPlugins.push(remarkUnwrapImages) + // Inject Gatsby path prefix if needed if (helpers.pathPrefix) { options.mdxOptions.remarkPlugins.push([ diff --git a/yarn.lock b/yarn.lock index 749b97db06735..5c263858b4cab 100644 --- a/yarn.lock +++ b/yarn.lock @@ -21556,6 +21556,16 @@ remark-toc@^5.0.0: mdast-util-toc "^2.0.0" remark-slug "^5.0.0" +remark-unwrap-images@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/remark-unwrap-images/-/remark-unwrap-images-3.0.1.tgz#22a547baa8fa1e2c66c7d087ebd9cf829a74a255" + integrity sha512-5VUY0n+J9lPTPfkct5S3/SbutryBjp8J/4mbgtlkDrOk3h8jde0hyqdYUJOoJKherZezS08tjd6i4+nnQ+wl5w== + dependencies: + "@types/mdast" "^3.0.0" + hast-util-whitespace "^2.0.0" + unified "^10.0.0" + unist-util-visit "^4.0.0" + remark@^13.0.0: version "13.0.0" resolved "https://registry.yarnpkg.com/remark/-/remark-13.0.0.tgz#d15d9bf71a402f40287ebe36067b66d54868e425"