2021-01-09 17:50:45 +08:00
|
|
|
const visit = require('unist-util-visit')
|
|
|
|
const sizeOf = require('image-size')
|
|
|
|
const fs = require('fs')
|
|
|
|
|
|
|
|
module.exports = (options) => (tree) => {
|
|
|
|
visit(
|
|
|
|
tree,
|
|
|
|
// only visit p tags that contain an img element
|
|
|
|
(node) => node.type === 'paragraph' && node.children.some((n) => n.type === 'image'),
|
|
|
|
(node) => {
|
|
|
|
const imageNode = node.children.find((n) => n.type === 'image')
|
|
|
|
|
|
|
|
// only local files
|
|
|
|
if (fs.existsSync(`${process.cwd()}/public${imageNode.url}`)) {
|
|
|
|
const dimensions = sizeOf(`${process.cwd()}/public${imageNode.url}`)
|
|
|
|
|
|
|
|
// Convert original node to next/image
|
2021-06-26 18:46:45 +08:00
|
|
|
;(imageNode.type = 'mdxJsxFlowElement'),
|
|
|
|
(imageNode.name = 'Image'),
|
|
|
|
(imageNode.attributes = [
|
|
|
|
{ type: 'mdxJsxAttribute', name: 'alt', value: imageNode.alt },
|
|
|
|
{ type: 'mdxJsxAttribute', name: 'src', value: imageNode.url },
|
|
|
|
{ type: 'mdxJsxAttribute', name: 'width', value: dimensions.width },
|
|
|
|
{ type: 'mdxJsxAttribute', name: 'height', value: dimensions.height },
|
|
|
|
])
|
2021-01-09 17:50:45 +08:00
|
|
|
|
|
|
|
// Change node type from p to div to avoid nesting error
|
|
|
|
node.type = 'div'
|
|
|
|
node.children = [imageNode]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
}
|