简体   繁体   English

使用纯JS在另一个JS文件中包含一个JS文件

[英]Include a JS file in another JS file with pure JS

I want to include a JS file in another JS file in pure JS, so without NPM or Yarn.我想在纯JS的另一个JS文件中包含一个JS文件,所以没有NPM或Yarn。

I do not use classes/modules, so how can I do this?我不使用类/模块,那么我该怎么做呢?

What I mean with Pure JS我对纯 JS 的意思

Pure JS is JavaScript that you directly can include in your HTML, like so:纯 JS 是可以直接包含在 HTML 中的 JavaScript,如下所示:

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

What I tried我试过的

Here are my two files:这是我的两个文件:

app.js

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

components/navbar.js

alert('Navbar component!');

But I get this error:但我收到此错误:

Uncaught ReferenceError: require is not defined

Because normal browsers don't know the require keyword.因为普通浏览器不知道 require 关键字。

Since you don't want to use modules you could load an additional script with an AJAX call and then use eval to run it.由于您不想使用模块,您可以使用 AJAX 调用加载额外的脚本,然后使用 eval 运行它。 This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model.这是最直接的方法,但由于 JavaScript 沙箱安全模型,它仅限于您的域。 Using eval also opens the door to bugs, hacks, and security issues.使用 eval 还为错误、黑客和安全问题打开了大门。 you can do it like so:你可以这样做:

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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM