xeyownt / mwpgnjs

A MediaWiki extension to display and animate chess games (boards and moves) given in PGN format
Apache License 2.0
3 stars 1 forks source link

TypeError: $.i18n is undefined when loading with ResourceLoader #3

Closed xeyownt closed 6 years ago

xeyownt commented 6 years ago

Module i18next used in PgnViewerJS does not export itself properly when we load PgnViewerJS with MW ResourceLoader. We get this error in browser console:

TypeError: $.i18n is undefined

Ideally it should attach itself to jQuery, but instead it exports itself by binding to module.exports as a nodejs module. See code:

    // Export the i18next object for **CommonJS**. 
    // If we're not in CommonJS, add `i18n` to the
    // global object or to jquery.
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = i18n;
    } else {
        if ($) {
            $.i18n = $.i18n || i18n;
        }

        if (root.i18n) {
            conflictReference = root.i18n;
        }
        root.i18n = i18n;
    }
xeyownt commented 6 years ago

One solution is to export ourselves i18next correctly. But there are some details to work around.

First, if we import PgnViewerJS with (file extension.json):

    "scripts": [
        "PgnViewerJS/dist/js/pgnvjs.js",
        "PgnJS.js"
    ]

Then in that case module.exports does no longer contain a reference to i18n. It is probably overwritten by another module loaded after i18next. Indeed, looking into PgnViewerJS/Gruntfile.js, we see that dist/js/pgnvjs.js is a concatenation of multiple JS libraries.

A simple fix is to make sure that i18next is the last library imported.

We modify our extension.json such as:

    "scripts": [
        "PgnViewerJS/dist/js/pgnvjs.js",
        "PgnViewerJS/js/i18next-1.11.2.js",
        "PgnJS.js"
    ]

Then, in PgnJS.js, we add:

// Let's export i18next correctly
$.i18n = $.i18n || module.exports;
i18n = $.i18n;
xeyownt commented 6 years ago

Another solution is not to use dist/js/pgnvjs.js, but list instead all libraries in extension.json (see issue #4) and make sure i18next-1.11.2.js is listed as the last library.