Dynamics CRM 365 – javascript ES6 modules (typescript)

0
50
Forum Post: Change the Filter On option on Opportunity Associated View for Account form


I am not using TypeScript but JavaScript.  I’ve already suggested that Microsoft fully support ES6 modules (please vote for it!) as modern browsers do and now IE is dead.  That said, I am using ES6 modules in CRM.

When your web resource is an HTML page it’s a non-issue because you can specify the <script type="module" src="..."></script> in HTML and it works.

When you are trying to supplement an existing form with a module (a JavaScript file not on an HTML web resource) it takes only a little work.

I created a script: new_ModuleLoader.js

function onModuleLoader(...modules){

  const load = setRelative("new_ModuleLoader.js");

  for(let mod of modules){

    load(mod);

  }

}

function setRelative(rel){

  const scripts = document.querySelectorAll('script')

  const srcs = Array.prototype.map.call(scripts, function(script){

    return script.src;

  });

  const root = srcs.find(function(src){

    return src.indexOf(rel) > -1;

  });

  return function load(url){

    const mod = document.createElement("script");

    const src = root.replace(rel, url);

    mod.type = "module";

    mod.src = src;

    document.body.appendChild(mod);

  }

}

 

I add the script to the page.  Then I add an on load event which points to onModuleLoader.  I do not pass in the context as there is no way I know of getting it to the module and that’s a problem Microsoft will solve when they get around to supporting modules.  I do however pass a Comma separated list of parameters that will be passed to the function.  I pass in the quoted names of the scripts to load (e.g. "new_MyModule.js","new_MyOtherModule.js").  The modules are dynamically added to the page and run just fine.

As you may be aware some of the Microsoft’s apis are deprecated.  We have been told to pass in context and not use Xrm.Page directly.  But since that doesn’t work on HTML page web resources, the Xrm.Page api remains available for that use case.  I have taken that same stance with the dynamically loaded ES6 modules as there is no choice until Microsoft decides to support them.  As far as I can tell, there is no reason Microsoft shouldn’t have this on their to-do list.



Source link

Leave a reply

Please enter your comment!
Please enter your name here