Fixing Mismatched Anonymous Define Module in Magento JS

javascriptmagento2modulerequirejs

I've tried adding my module JS file to Magento2 but for whatever reason it seems to return this error:

Error: Mismatched anonymous define() module: function($)

My view/frontend file structure:

|-frontend
|-----layout
|---------default_head_blocks.xml
|-----requirejs-config.js
|-----templates
|---------helloworld.phtml
|-----web
|---------js
|-------------main.js

requirejs-config.js

var config = {
    deps: [
        'js/main'
    ]
};

web/js/main.js

define(
    ['jquery'],
    function($)
    {
        "use strict";
        console.log('hello world');
    }
);

layout/default_head_blocks.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <script src="js/main.js" />
    </head>
</page>

What am I doing wrong in including my JS?

Best Answer

What are you doing wrong by including your JS is that your js file main.js, you should declare it in requirejs-config.js and not in default_head_blocks.xml

Here is a full exemple:

  1. app/code/Vendor/Module/view/frontend/requirejs-config.js
var config = {
    map: {
        '*': {
            module: 'Vendor_module/js/main',
        }
    }
};
  1. app/code/Vendor/Module/view/frontend/web/js/main.js
define(['jquery'], function($){
   "use strict";
       return function myscript()
       {
           alert('hello myscript');
           //put all your mainjs code here
       }
});
  1. app/code/Vendor/Module/view/frontend/templates/file.phtml
<script type="text/javascript">
    require(['jquery', 'module'], function($, myscript) {
        myscript();
    });
</script>

Don't forget to :

  • clean the cache

  • clean var/view_preprocessed content

  • clean pub/static content

  • deploy the static content : php bin/magento setup:static-content:deploy -f