【问题标题】:Import classic Javascript file导入经典 Javascript 文件
【发布时间】:2020-09-04 15:50:04
【问题描述】:

我有一个无法编辑的依赖经典 JavaScript 文件,我需要导入。它看起来像这样:

function DependencyInterface()
{
}

DependencyInterface.Foo = 'bar';

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

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

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

我想用它,像这样:

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

不幸的是,我收到如下错误:

  • “DependencyInterface”未定义(no-undef)
  • “DependencyPayload”未定义(no-undef)

我从这篇文章 (ES6 import equivalent of require() without exports) 中了解到,像这样的导入语句是块作用域的,唯一通过的是导出的内容。

我发现解决此问题的唯一方法是将依赖文件放在公共静态位置并在我的根 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>

但我真的很讨厌这个解决方案。它既不干净也不可扩展。

有什么方法可以导入这个经典的 JavaScript 文件吗?谢谢!

【问题讨论】:

    标签: javascript webpack


    【解决方案1】:

    恐怕不会。您的解决方案是唯一的等待。您可以通过使用动态更新 DOM 以插入 script 标记并在正确加载外部依赖项后执行包含其余代码的回调的函数来使其“更干净”。比如:

    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...
    });
    

    【讨论】:

      猜你喜欢
      • 2012-05-30
      • 1970-01-01
      • 2021-03-01
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-28
      • 1970-01-01
      相关资源
      最近更新 更多