I am trying to get constant contacts script to work with magento 2 requirejs. (I tried adding it inline but it conflicts and causes errors)
Their script requires an array localizedErrMap
and jQuery
object.
I created localizedErrMap.js
define([],
function(){
var localizedErrMap = {};
localizedErrMap['required'] = 'This field is required.';
localizedErrMap['ca'] = 'An unexpected error occurred while attempting to send email.';
localizedErrMap['email'] = 'Please enter your email address in [email protected] format.';
localizedErrMap['birthday'] = 'Please enter birthday in MM/DD format.';
localizedErrMap['anniversary'] = 'Please enter anniversary in MM/DD/YYYY format.';
localizedErrMap['custom_date'] = 'Please enter this date in MM/DD/YYYY format.';
localizedErrMap['list'] = 'Please select at least one email list.';
localizedErrMap['generic'] = 'This field is invalid.';
localizedErrMap['shared'] = 'Sorry, we could not complete your sign-up. Please contact us to resolve this.';
localizedErrMap['state_mismatch'] = 'Mismatched State/Province and Country.';
localizedErrMap['state_province'] = 'Select a state/province';
localizedErrMap['selectcountry'] = 'Select a country';
return localizedErrMap;
}
);
and made this requirejs-config.js
var config = {
"shim": {
"constantcontact": {
"deps":["jquery", "localizedErrMap"],
"depnames":["jQuery", "localizedErrMap"]
}
},
"paths": {
"localizedErrMap": "js/localizedErrMap",
"constantcontact": "https://static.ctctcdn.com/h/contacts-embedded-signup-assets/1.0.2/js/signup-form"
}
};
Then called it in the page with constant contact form like this:
<script>
require(["constantcontact"]);
</script>
Their script throws the error:
Uncaught ReferenceError: localizedErrMap is not defined
I cant modify their code as it’s offsite, I need to make sure this array is passed through to the code. What did I do wrong and how can I make sure the array is passed across?
2
Answers
I got it working by adding this to the CMS page inline.
That
depnames
array you are using inshim
is not something that RequireJS supports. The only reference I can find to it is in an issue report where someone suggested supporting such an option but that was never implemented.It looks like
constantcontact
, which is not an AMD module, expects to find a symbollocalizedErrMap
in the global space. In general, you have a few options:You can add a build step to how you build your application to add a
define
call around the code inconstantcontact
, effectively turning it into an AMD-module. ThewrapShim
option ofr.js
can be useful for this. However, you say that you cannot modify it so this option is off the table.You can deliberately leak
localizedErrMap
. Such leaking is sometimes a viable solution for using libraries that are not AMD libraries. I prefer to avoid it but there are situations where it cannot be avoided.