Skip to content

Commit

Permalink
fix: eslint rule of using img in metadata routes (#74864)
Browse files Browse the repository at this point in the history
  • Loading branch information
huozhi committed Jan 17, 2025
1 parent e204a30 commit 1882acb
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
17 changes: 17 additions & 0 deletions packages/eslint-plugin-next/src/rules/no-img-element.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import path = require('path')
import { defineRule } from '../utils/define-rule'

const url = 'https://nextjs.org/docs/messages/no-img-element'
Expand All @@ -15,6 +16,14 @@ export = defineRule({
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') {
Expand All @@ -29,6 +38,14 @@ export = defineRule({
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}`,
Expand Down
61 changes: 61 additions & 0 deletions test/unit/eslint-plugin-next/no-img-element.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,46 @@ const tests = {
);
}
}`,
{
code: `\
import { ImageResponse } from "next/og";
export default function icon() {
return new ImageResponse(
(
<img
alt="avatar"
style={{ borderRadius: "100%" }}
width="100%"
height="100%"
src="https://example.com/image.png"
/>
)
);
}
`,
filename: `src/app/icon.js`,
},
{
code: `\
import { ImageResponse } from "next/og";
export default function Image() {
return new ImageResponse(
(
<img
alt="avatar"
style={{ borderRadius: "100%" }}
width="100%"
height="100%"
src="https://example.com/image.png"
/>
)
);
}
`,
filename: `app/opengraph-image.tsx`,
},
],
invalid: [
{
Expand Down Expand Up @@ -91,6 +131,27 @@ const tests = {
}`,
errors: [{ message, type: 'JSXOpeningElement' }],
},
{
code: `\
import { ImageResponse } from "next/og";
export default function Image() {
return new ImageResponse(
(
<img
alt="avatar"
style={{ borderRadius: "100%" }}
width="100%"
height="100%"
src="https://example.com/image.png"
/>
)
);
}
`,
filename: `some/non-metadata-route-image.tsx`,
errors: [{ message, type: 'JSXOpeningElement' }],
},
],
}

Expand Down

0 comments on commit 1882acb

Please sign in to comment.