eslint-plugin-green
Version:
ESLint plugin for evaluating and promoting green coding practices
52 lines (51 loc) • 2.07 kB
JavaScript
;
const rule = {
meta: {
type: 'suggestion',
docs: {
description: 'Enforce efficient image loading practices',
category: 'Media',
recommended: true,
},
schema: [], // no options
},
create(context) {
return {
CallExpression(node) {
if (node.callee.type === 'MemberExpression') {
const callee = node.callee;
if (callee.property.type === 'Identifier') {
const methodName = callee.property.name;
// Check for Image constructor usage
if (methodName === 'Image' && callee.object.type === 'Identifier' &&
callee.object.name === 'window') {
context.report({
node,
message: 'Consider using the native <img> element with loading="lazy" for better energy efficiency'
});
}
}
}
},
JSXOpeningElement(node) {
if (node.name.name === 'img') {
const hasLazyLoading = node.attributes.some((attr) => attr.name.name === 'loading' && attr.value.value === 'lazy');
const hasSizes = node.attributes.some((attr) => attr.name.name === 'sizes');
if (!hasLazyLoading) {
context.report({
node,
message: 'Add loading="lazy" to images below the fold for better energy efficiency'
});
}
if (!hasSizes) {
context.report({
node,
message: 'Add sizes attribute to help browser select the right image size'
});
}
}
}
};
}
};
module.exports = rule;