Search code examples
javascriptecmascript-6compilationgoogle-closure-compilerarrow-functions

ERROR - [JSC_UNDEFINED_VARIABLE] variable previousPage is undeclared - Google Closure Compiler


I'm compiling 2 x JS files using Google Closure templates. And for some reason, it simply does not like my arrow functions. For example:

// let showCurrentPage;
showCurrentPage = (i) => {
    currentPage = i;
    paginationCountLogic(bookMarksArray);
}

If I change to a different function type, for example:

    let showCurrentPage = function(i) {
        currentPage = i;
        paginationCountLogic(bookMarksArray);
    }

My function becomes usable or recognised in my JS file.

'showCurrentPage' is declared but its value is never read.ts(6133)

My code works fine, without compilation. And I have been googling for hours, but I can not seem to fix this.

I have even tried changing my NPM command, to compile from ES6 to ES5. But this does not seem to fixe the issue:

npx google-closure-compiler --js=app.js --js=pagination.js  --compilation_level ADVANCED_OPTIMIZATIONS --language_in ECMASCRIPT6  --language_out ECMASCRIPT5 --js_output_file=minified.js

Any ideas?

Here's the actual error:

pagination.js:43: ERROR - [JSC_UNDEFINED_VARIABLE] variable showCurrentPage is undeclared
    showCurrentPage = (i) => {
    ^^^^^^^^^^^^^^^

Solution

  • I got this answered via another question. But this turns out to be the reason why:

    The cause is probably that the compiler doesn't see the function being called. Part of the advanced compilation is removing unused code and renaming the methods/variables.

    Within your js or html it is never called because the function call is only defined in a string value here :

    for (var i = 0; i < individualPagesArray.length; i++) {
       document.getElementById("numbers").innerHTML += `<button onclick=showCurrentPage(${i+1})>` + individualPagesArray[i] + `</button>`;
    }
    

    you can solve this pretty simply by rewriting this:

    window.showCurrentPage = (i) => {
    

    to this:

    window['showCurrentPage'] = (i) => {
    

    See : https://developers.google.com/closure/compiler/docs/api-tutorial3#removal