我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?


当前回答

我用另一种方法尝试了这个问题。

命令导入脚本,在这里没有效应。

標籤:HTML

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Trials</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="main.js"></script>
    <script src="scriptA.js"></script>
</head>

<body>
<h3>testing js in js (check console logs)</h3>
<button onclick="fnClick()">TEST</button>
</body>

</html>

主.js

function fnClick() {
  console.log('From\tAAAAA');
  var pro = myExpo.hello();
  console.log(pro);
}

编辑:JS

myExpo = {
    hello: function () {
        console.log('From\tBBBBB');
        return "Hello";
    }
}

而结果是

From    AAAAA
From    BBBBB
Hello

其他回答

如果有人正在寻找一些更先进的东西,试试 RequireJS. 你会得到添加的好处,如依赖管理,更好的竞争,并避免复制(即,获得一个脚本超过一次)。

您可以将 JavaScript 文件写入“模块”,然后将其列为其他脚本中的依赖,或者您可以使用 RequireJS 作为一个简单的“去获取这个脚本”解决方案。

例子:

将依赖定义为模块:

某些依赖性.js

define(['lib/dependency1', 'lib/dependency2'], function (d1, d2) {

     //Your actual script goes here.   
     //The dependent scripts will be fetched if necessary.

     return libraryObject;  //For example, jQuery object
});

implementation.js 是您的“主要” JavaScript 文件,取决于某些 dependency.js

require(['some-dependency'], function(dependency) {

    //Your script goes here
    //some-dependency.js is fetched.   
    //Then your script is executed
});

從 GitHub README 發表:

RequireJS 加载平面 JavaScript 文件以及更定义的模块. 它是优化在浏览器中的使用,包括在 Web 工作者,但它可以用于其他 JavaScript 环境,如 Rhino 和 Node. 它实施了 Asynchronous 模块 API. RequireJS 使用平面脚本标签加载模块/文件,所以它应该允许轻松的解体。

ES6 模块

是的,在脚本标签(支持)中使用 type="module" :

<script type="module" src="script.js"></script>

在一个 script.js 文件中包含另一个文件如下:

import { hello } from './module.js';
...
// alert(hello());

在“module.js”中,您必须导出您将导入的函数/类:

export function hello() {
    return "Hello World";
}

這裡有一個工作例子。

对于 Node.js 而言,这对我来说是最好的!

我在这里尝试了很多解决方案,但没有一个帮助我只是能够在没有改变范围的情况下加载另一个文件。

const fs = require('fs');
eval(fs.readFileSync('file.js') + '');

也许你可以使用我在此页面上发现的这个功能 如何将JavaScript文件纳入JavaScript文件中?

function include(filename)
{
    var head = document.getElementsByTagName('head')[0];

    var script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';

    head.appendChild(script)
}

另一种方式,在我看来是更清洁的,是做一个同步的Ajax请求而不是使用一个<script>标签。

下面是使用 jQuery 的例子:

function require(script) {
    $.ajax({
        url: script,
        dataType: "script",
        async: false,           // <-- This is the key
        success: function () {
            // all good...
        },
        error: function () {
            throw new Error("Could not load script " + script);
        }
    });
}

然后你可以在你的代码中使用它,因为你通常会使用一个包括:

require("/scripts/subscript.js");

并能够在下列行中从所需脚本中呼叫一个函数:

subscript.doSomethingCool();