首页 > 解决方案 > 用纯 JS 在另一个 JS 文件中包含一个 JS 文件

问题描述

我想在纯 JS 的另一个 JS 文件中包含一个 JS 文件,所以没有 NPM 或 Yarn。

我不使用类/模块,那么我该怎么做呢?

我对纯 JS 的意思

Pure JS 是可以直接包含在 HTML 中的 JavaScript,如下所示:

<script src="path/to/pure-js-file.js"></script>

我试过的

这是我的两个文件:

app.js

require('./components/navbar.js');

components/navbar.js

alert('Navbar component!');

但我得到这个错误:

Uncaught ReferenceError: require is not defined

因为普通浏览器不知道 require 关键字。

标签: javascript

解决方案


由于您不想使用模块,您可以使用 AJAX 调用加载附加脚本,然后使用 eval 运行它。这是最直接的方法,但由于 JavaScript 沙盒安全模型,它仅限于您的域。使用 eval 还为漏洞、黑客和安全问题打开了大门。你可以这样做:

function getFile(filePath) {
    var httpRequest = new XMLHttpRequest();

    if (!httpRequest) {
      alert('Cannot create an XMLHTTP instance');
      return false;
    }

    httpRequest.onreadystatechange = function() {
      if (httpRequest.readyState === XMLHttpRequest.DONE) {
        if (httpRequest.status === 200) {
          eval(httpRequest.responseText);
        } else {
          alert('There was a problem with the request.');
        }
      }
    };

    httpRequest.open('GET', filePath);
    httpRequest.send();
}

getFile('./components/navbar.js');

推荐阅读