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 inrequirejs-config.js
and not indefault_head_blocks.xml
Here is a full exemple:
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