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


当前回答

是的,有......

在 ES6 中,我们可以将部分或整个JavaScript文件导出并导入到另一个文件中。

但等待,ES6不支持所有浏览器,所以你需要通过 babel.js 使用它,例如...

所以你创建一个类如下:

class Person {
  constructor(name) {
    this.name = name;
  }

  build() {
    return new Person(this);
  }
}

module.exports = Person;

import { Person } from 'Person';

您也可以要求文件如:

const Person = require('./Person');

如果您正在使用更古老的 JavaScript 版本,您可以使用 requirejs:

requirejs(["helper/util"], function(util) {
    // This function is called when scripts/helper/util.js is loaded.
    // If util.js calls define(), then this function is not fired until
    // util's dependencies have loaded, and the util argument will hold
    // the module value for "helper/util".
});

如果你想坚持旧版本的物品,如jQuery,你也可以使用一些东西,如 getScript:

jQuery.getScript('./another-script.js', function() {
    // Call back after another-script loaded
});

最后,但不要忘记,你可以用 <script> 标签一起编写脚本的传统方式。

<script src="./first-script.js"></script>
<script src="./second-script.js"></script>
<script src="./third-script.js"></script>

注意: 有几种方式可以执行一个外部脚本: 如果 async 存在: 脚本与页面剩余的同步执行(脚本将执行,而页面继续播放) 如果 async 没有存在,并且 defer 存在: 脚本在页面完成播放时执行 如果没有 async 或 defer 存在: 脚本被捕并执行 imme

其他回答

最好使用 jQuery 方式. 要延迟已准备的事件,首先拨打 $.holdReady(真实)。

$.holdReady(true);
$.getScript("myplugin.js", function() {
    $.holdReady(false);
});

你不能进口,但你可以参考。

PhpShtorm IDE. 要提到,在一个.js 文件到另一个.js,只需将此添加到文件的顶部:

<reference path="../js/file.js" />

当然,你应该使用自己的PATH到JavaScript文件。

我不知道它是否会在其他IDES中工作,也许是的,只是试试,它也应该在Visual Studio中工作。

在这里展示的大多数解决方案都意味着动态加载. 我正在寻找一个编译器,将所有依赖的文件集成到一个单一的输出文件. 相同的Less/Sass预处理器处理CSS @import在规则上. 因为我找不到任何值得这个类型的东西,我写了一个简单的工具解决问题。

因此,这里是编译器, https://github.com/dsheiko/jsic,它取代 $import(“文件路径”)与请求的文件内容安全。

主 / 主 / JS

var foo = $import("./Form/Input/Tel");

src / 表格 / 输入 / Tel.js

function() {
    return {
          prop: "",
          method: function(){}
    }
}

现在我们可以运行编辑器:

node jsic.js src/main.js build/mail.js

接收合并文件

主 / 主 / JS

var foo = function() {
    return {
          prop: "",
          method: function(){}
    }
};

与 $.getScript 和实际上任何其他解决方案需要一个呼叫回复,当加载完成时的问题是,如果你有多个文件使用它,并依赖对方,你已经没有办法知道什么时候所有的脚本被加载(一旦它们被纳入多个文件)。

文件3JS

var f3obj = "file3";

// Define other stuff

文件2JS:

var f2obj = "file2";
$.getScript("file3.js", function(){

    alert(f3obj);

    // Use anything defined in file3.
});

此分類上一篇: JS

$.getScript("file2.js", function(){
    alert(f3obj); //This will probably fail because file3 is only guaranteed to have loaded inside the callback in file2.
    alert(f2obj);

    // Use anything defined in the loaded script...
});

您可以尝试使用 $.when 检查一系列丢失的对象,但现在您正在做这一点在每个文件和文件2 将被视为加载,一旦 $.when 执行,而不是当呼叫回复执行,所以文件1 仍然继续执行之前文件3 被加载,这真的仍然有相同的问题。

我喜欢延长jQuery的想法,但显然你不需要。

在呼叫document.writeln之前,它检查以确保脚本已经没有被加载,通过评估所有脚本元素。

而不是这个方法,你可以尝试修改 jQuery readyList,但这似乎是一个更糟糕的解决方案。

解决方案:

$.extend(true,
{
    import_js : function(scriptpath, reAddLast)
    {
        if (typeof reAddLast === "undefined" || reAddLast === null)
        {
            reAddLast = true; // Default this value to true. It is not used by the end user, only to facilitate recursion correctly.
        }

        var found = false;
        if (reAddLast == true) // If we are re-adding the originating script we do not care if it has already been added.
        {
            found = $('script').filter(function () {
                return ($(this).attr('src') == scriptpath);
            }).length != 0; // jQuery to check if the script already exists. (replace it with straight JavaScript if you don't like jQuery.
        }

        if (found == false) {

            var callingScriptPath = $('script').last().attr("src"); // Get the script that is currently loading. Again this creates a limitation where this should not be used in a button, and only before document.ready.

            document.writeln("<script type='text/javascript' src='" + scriptpath + "'></script>"); // Add the script to the document using writeln

            if (reAddLast)
            {
                $.import_js(callingScriptPath, false); // Call itself with the originating script to fix the order.
                throw 'Readding script to correct order: ' + scriptpath + ' < ' + callingScriptPath; // This halts execution of the originating script since it is getting reloaded. If you put a try / catch around the call to $.import_js you results will vary.
            }
            return true;
        }
        return false;
    }
});

使用:

var f3obj = "file3";

// Define other stuff
$(function(){
    f3obj = "file3docready";
});

文件2:

$.import_js('js/file3.js');
var f2obj = "file2";
$(function(){
    f2obj = "file2docready";
});

文件1:

$.import_js('js/file2.js');

// Use objects from file2 or file3
alert(f3obj); // "file3"
alert(f2obj); // "file2"

$(function(){
    // Use objects from file2 or file3 some more.
    alert(f3obj); //"file3docready"
    alert(f2obj); //"file2docready"
});

使用 ES6 的进口和出口模块与 Node.js 合作

使用.mjs 扩展而不是.js 的名称文件

创建文件

touch main.mjs lib.mjs

主.js

import { add } from './lib.mjs';
console.log(add(40, 2));

英格兰MJ

export let add = (x,y) => {
  return x + y
}

跑步

node --experimental-modules main.js