File size: 1,523 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
import path = require('path')
import { defineRule } from '../utils/define-rule'
const url = 'https://nextjs.org/docs/messages/no-img-element'
export = defineRule({
meta: {
docs: {
description:
'Prevent usage of `<img>` element due to slower LCP and higher bandwidth.',
category: 'HTML',
recommended: true,
url,
},
type: 'problem',
schema: [],
},
create(context) {
// Get relative path of the file
const relativePath = context.filename
.replace(path.sep, '/')
.replace(context.cwd, '')
.replace(/^\//, '')
const isAppDir = /^(src\/)?app\//.test(relativePath)
return {
JSXOpeningElement(node) {
if (node.name.name !== 'img') {
return
}
if (node.attributes.length === 0) {
return
}
if (node.parent?.parent?.openingElement?.name?.name === 'picture') {
return
}
// If is metadata route files, ignore
// e.g. opengraph-image.js, twitter-image.js, icon.js
if (
isAppDir &&
/\/opengraph-image|twitter-image|icon\.\w+$/.test(relativePath)
)
return
context.report({
node,
message: `Using \`<img>\` could result in slower LCP and higher bandwidth. Consider using \`<Image />\` from \`next/image\` or a custom image loader to automatically optimize images. This may incur additional usage or cost from your provider. See: ${url}`,
})
},
}
},
})
|