Magento – Magento 2: Mismatched anonymous define() module

magento2requirejs

I passed a variable from phtml to js it's working fine but it shows "Mismatched anonymous define() module" error in console.

Phtml File:

<?php $myVar = "This is my value" ?>

<script type="text/x-magento-init">
   {
        "*": {
            "Prince_Faq/js/faq": {
                "animateSpeed": "<?php echo $myVar ?>"
            }
        }
    }
</script>

I tried after changing define() to require(), The error was gone but variable not getting value from config.

Js File:

define ([
    'jquery', 
    'jquery/ui'
], function($){
    'use strict';

    return function (config) {
        alert(config.animateSpeed); //Not getting value after changing to require()
    };
});

Best Answer

As a last resort you could try rendering the contents within Knockout JS as I know that definitely works:

app/code/VENODR/MODULE/view/frontend/templates/knockout-example.phtml

<script type="text/x-magento-init">
{
    "*": {
        "Magento_Ui/js/core/app": {
            "components": {
                "example-scope": {
                    "component": "VENDOR_MODULE/js/knockout-example",
                    "exampleMessage": "<?= __('Hello Magento Stack Exchange!') ?>"
                }
            }
        }
    }
}
</script>

<div data-bind="scope: 'example-scope'">
    <h2 data-bind="text: message"></h2>
</div>

app/code/VENDOR/MODULE/view/frontend/web/js/knockout-example.js

define(['ko'], function(ko) {
    return function(config) {
        this.message = ko.observable(config.exampleMessage);
    }
});

Changing my example message with your variable.

Related Topic