Skip to content

Instantly share code, notes, and snippets.

@image72
Created February 9, 2025 15:03
Show Gist options
  • Save image72/d1229c53d0dd27a6fc2b7106c92ef381 to your computer and use it in GitHub Desktop.
Save image72/d1229c53d0dd27a6fc2b7106c92ef381 to your computer and use it in GitHub Desktop.
eslint, forbid native navigations in vue components.
// lib/rules/no-native-navigation.js
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'Forbid native navigation methods in Vue components',
category: 'Best Practices',
recommended: true,
},
fixable: null,
schema: [], // no options
messages: {
avoidNativeNavigation: 'Avoid using native navigation methods. Use Vue Router methods instead.',
},
},
create(context) {
// Check if the current file is a Vue component
const isVueComponent = context.getFilename().endsWith('.vue');
// If not a Vue component, return an empty object to skip checks
if (!isVueComponent) {
return {};
}
return {
MemberExpression(node) {
// Check for location.href
if (
node.object.type === 'Identifier' &&
node.object.name === 'location' &&
node.property.type === 'Identifier' &&
node.property.name === 'href'
) {
context.report({
node,
messageId: 'avoidNativeNavigation',
});
}
// Check for history.go, history.push, etc.
if (
node.object.type === 'Identifier' &&
node.object.name === 'history' &&
['go', 'push', 'replace', 'back', 'forward'].includes(node.property.name)
) {
context.report({
node,
messageId: 'avoidNativeNavigation',
});
}
},
CallExpression(node) {
// Additional check for window.location methods
if (
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'Identifier' &&
node.callee.object.name === 'location' &&
['assign', 'replace'].includes(node.callee.property.name)
) {
context.report({
node,
messageId: 'avoidNativeNavigation',
});
}
}
};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment