eslinttypescript-eslint

Is there a way to restrict the usage of JSON.stringify with ESLint and after linting giving an error to use my own utility function?


I have a utility function which adds some additional error handling for JSON.stringify. Is there some rules in eslint which can restrict global functions for example JSON.stringify with ESLint and after linting giving an error to use my own utility function? And how could I restrict it only to ts and tsx files?

I tried to use the no-restricted-globals rules, but it didnt solved the problem and then I used no-restricted syntax and it looks like it could work, but I am not sure how to use it and how to restrict to only ts and tsx


Solution

  • You can write your own rule, Inside the eslint-custom-rules directory, create a file no-json-stringify.js

    module.exports = {
    meta: {
        type: 'problem',
        docs: {
            description: 'disallow usage of JSON.stringify and suggest using myUtilityFunction instead',
            category: 'Best Practices',
            recommended: false,
        },
        messages: {
            avoidJSONStringify: 'Avoid using JSON.stringify. Use myUtilityFunction instead.',
        },
        schema: [], // no options
    },
    create(context) {
        return {
            CallExpression(node) {
                if (
                    node.callee.type === 'MemberExpression' &&
                    node.callee.object.name === 'JSON' &&
                    node.callee.property.name === 'stringify'
                ) {
                    context.report({
                        node,
                        messageId: 'avoidJSONStringify',
                    });
                }
            },
        };
    },
    

    };

    Update the .eslintrc.js file:

    Add the custom rule to your ESLint configuration

    module.exports = {
    // Other ESLint configuration options
    plugins: [
        'eslint-plugin-custom-rules', // Name of your custom rules plugin
    ],
    rules: {
        'custom-rules/no-json-stringify': 'error', // Enforce the custom rule
    },
    // Path to custom rules
    settings: {
        'import/resolver': {
            node: {
                paths: ['eslint-custom-rules'],
            },
        },
    },
    

    };

    Ensure that the custom rule is recognized by ESLint. You may need to configure the plugin loading if necessary, depending on your project setup.

    Hope this help