Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I `eslint` my JavaScript when it depends on objects from previously loaded scripts?

I am wanting to add eslint to my WordPress plugin. But I keep getting an error message about an undefined name. At runtime, the name is defined by a previously loaded script within the browser. How can I get eslint to recognize that this particular name is okay?

Error from eslint::

/js/plugin.js
    13:12   error  'Cookies' is not defined                                    no-undef

My plugin's php loads the javascript files in the WordPress-way, using wp_enqueue_script. My plugin's javascript is dependent upon jquery and js-cookie, and js-cookie is dependent upon jquery. Therefore, Wordpress will ensure that the <script> for js-cookie comes before the <script> for my plugin.

plugin.php:

    wp_enqueue_script( 'js-cookie', $path . 'inc/js.cookie.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'plugin-js', $path . 'js/plugin.min.js', array( 'jquery', 'js-cookie' ), '1.2.1', true );

My plugin's javascript uses the Cookies object to do various things.

plugin.js:

(function($) {
    $.ajax({
        url: '/wp-json/plugin-name/v1/method',
        dataType: 'json',
        success: function( data ) {
            process( data );
        },
        error: function(e) {
            console.log(e);
        }
    });
    function process(data) {
        if (Cookies.get('cookie-name'){
            ...
        }
    }
}(jQuery));
like image 684
parleer Avatar asked Oct 23 '25 01:10

parleer


1 Answers

You can specify Cookies as an externally-defined "global" in the file in which you use it. Add this to the beginning of plugin.js:

/* global Cookies */

You can also declare it in a configuration file, but this is less likely to be helpful to you given that it sounds like you are also defining Cookies (and thus it should not be declared as a pre-existing global in the file in which you define it).

See the ESLint documentation on specifying globals.

like image 50
David P. Caldwell Avatar answered Oct 24 '25 17:10

David P. Caldwell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!