Skip to content

Commit

Permalink
fix(gatsby-plugin-mdx) for image import name collisions in mdx files
Browse files Browse the repository at this point in the history
This commit allows importing files with the same import name across different files.
Tries to be valid for `import pic from file.jpeg` or `import * as pic from file.jpeg` imports.
  • Loading branch information
illogic-al committed Mar 2, 2022
1 parent 3b8710c commit b875961
Showing 1 changed file with 41 additions and 2 deletions.
43 changes: 41 additions & 2 deletions packages/gatsby-plugin-mdx/gatsby/on-create-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,51 @@ async function onCreateNode(api, pluginOptions) {
return
}

/** @type string */
const content = await api.loadNodeContent(api.node)

/** Captures the import name when used on a file with an extension up to 4 chars long. e.g
* `import pic from file.jpeg` or `import * as pic from file.jpeg` */
const importFinderRegexp = `import {?(?:\\*\\s+as\\s+)?(.*)(?:}?\\s*from\\s+['"].*\\.(?:avif|bmp|jpe?g|gif|png|svg|webp)['"])`
/** An array of file imports, e.g. `import pic from file.jpeg`
* @type RegExpMatchArray */
let fileImports = []
/** @type string[] */
let namedImports = []
Array.from(content.matchAll(RegExp(importFinderRegexp, 'gm')), (search, idx) => {
fileImports[idx] = search[0]
namedImports[idx] = search[1]
})
const importId = api.node.id.replace(/-/g,'')

const renamedImports = fileImports?.map((fileImport, index) => {
return fileImport.replace(namedImports[index], `${namedImports[index].trim()}_${importId} `)
})

/** @type string */
let fixedContent = content
if (fileImports?.length !== renamedImports?.length) {
// Throw error
api.reporter.error("Error: the number of namespaced imports and found imports do not match in gatsby-plugin-mdx's onCreateNode")
} else {
try {
fileImports.length > 0 && fileImports.forEach((item, index) => {
const namedImport = namedImports[index].trim()
fixedContent = fixedContent
// 1st replacement: replace given import, with uid postfixed imports
.replace(item, renamedImports[index])
// 2nd replacement: check for src={importName} and globally replace it regardless of surrounding space
.replace(RegExp(`src={ *?${namedImport} *?}`, 'gm'), `src={${namedImport}_${importId}}`)
})
} catch(err) {
api.reporter.error("Error when creating namespaced imports in gatsby-plugin-mdx")
}
}

if (options.lessBabel) {
await onCreateNodeLessBabel(content, api, options)
await onCreateNodeLessBabel(fixedContent, api, options)
} else {
await onCreateNodeExtraBabel(content, api, options)
await onCreateNodeExtraBabel(fixedContent, api, options)
}
}

Expand Down

0 comments on commit b875961

Please sign in to comment.