0

I have a dependent classic JavaScript file which I cannot edit and I need to import. It looks like this:

function DependencyInterface()
{
}

DependencyInterface.Foo = 'bar';

DependencyInterface.prototype.one = 1;
DependencyInterface.prototype.two = 1;

DependencyInterface.prototype.doSomething = function(dependencyPayload) {
  // ...
}

function DependencyPayload(value) {
  this.value = value;
}

I would like to use it, like this:

import '@/scripts/DependencyInterface.js'
let dependencyInterface = new DependencyInterface();
dependencyInterface.doSomething(new DependencyPayload(3));

Unfortunately I am getting errors like:

  • 'DependencyInterface' is not defined (no-undef)
  • 'DependencyPayload' is not defined (no-undef)

I read from this post (ES6 import equivalent of require() without exports) that import statements like this are block scoped, and the only thing through are what is exported.

The only way around this I have found is to the dependency file in a public static location and do this in my root HTML:

<script type="text/javascript" src="<%= BASE_URL %>js/DependencyInterface.js"></script>
<script type="text/javascript">
  window.createDependencyInterface = function() { return new DependencyInterface() };
  window.createDependencyPayload = function(value) { return new DependencyPayload(value); }
</script>

But I really hate this solution. It isn't clean or scalable.

Is there any way to import this classic JavaScript file? Thanks!

Agendum
  • 1,697
  • 1
  • 18
  • 36

1 Answers1

0

I'm afraid not. Your solution is the only wait to do so. You can make it "cleaner" by using a function that dynamically updates the DOM to insert that script tag and executes a callback containing the rest of your code once the external dependency has correctly been loaded. Something like:

function loadScript(script, callback) {
  const dom = document.createElement('script');
  if (callback) dom.onload = callback;
  dom.type = (script.type) ? script.type : 'text/javascript';
  if (typeof (script) === 'object') {
    if (script.src) dom.src = script.src;
    if (script.integrity) dom.integrity = script.integrity;
    if (script.crossorigin) dom.crossOrigin = script.crossorigin;
  } else if (typeof (script) === 'string') {
    dom.src = script;
  }
  document.getElementsByTagName('head')[0].appendChild(dom, document.currentScript);
}

loadScript({ src: '<%= BASE_URL %>js/DependencyInterface.js' }, function () {
   // Your code here...
});