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


当前回答

我只是写了这个JavaScript代码(使用DOM操作的Prototype):

var require = (function() {
    var _required = {};
    return (function(url, callback) {
        if (typeof url == 'object') {
            // We've (hopefully) got an array: time to chain!
            if (url.length > 1) {
                // Load the nth file as soon as everything up to the
                // n-1th one is done.
                require(url.slice(0, url.length - 1), function() {
                    require(url[url.length - 1], callback);
                });
            } else if (url.length == 1) {
                require(url[0], callback);
            }
            return;
        }
        if (typeof _required[url] == 'undefined') {
            // Haven't loaded this URL yet; gogogo!
            _required[url] = [];

            var script = new Element('script', {
                src: url,
                type: 'text/javascript'
            });
            script.observe('load', function() {
                console.log("script " + url + " loaded.");
                _required[url].each(function(cb) {
                    cb.call(); // TODO: does this execute in the right context?
                });
                _required[url] = true;
            });

            $$('head')[0].insert(script);
        } else if (typeof _required[url] == 'boolean') {
            // We already loaded the thing, so go ahead.
            if (callback) {
                callback.call();
            }
            return;
        }

        if (callback) {
            _required[url].push(callback);
        }
    });
})();

使用:

<script src="prototype.js"></script>
<script src="require.js"></script>
<script>
    require(['foo.js','bar.js'], function () {
        /* Use foo.js and bar.js here */
    });
</script>

地址: http://gist.github.com/284442.

其他回答

我来到这个问题,因为我正在寻找一个简单的方式来保持一个收藏有用的JavaScript插件。

设置一个名为“plugins.js”的文件(或 extensions.js 或任何你想要的)。 保持你的插件文件与一个主文件。

//set array to be updated when we add or remove plugin files
var pluginNames = ["lettering", "fittext", "butterjam", etc.];

//one script tag for each plugin
$.each(pluginNames, function(){
    $('head').append('<script src="js/plugins/' + this + '.js"></script>');
});

手动呼叫你的头中的一个文件: <script src="js/plugins/plugins.js"></script>

但是:

雖然所有插件都落入頭標籤的方式,他們不總是通過瀏覽器,當你點擊到頁面或更新。

假设您想将 A.js 文件导入到 B.js 文件中。

现在肯定您已将 B.js 链接到 HTML 文件中,然后只需在 B.js 之前将 A.js 链接到 HTML 文件中。

这并不需要一个复杂的答案。

另一个方法是使用HTML进口,这些可以包含脚本参考以及风格表参考。

您可以将 HTML 文件链接到

<link rel="import" href="vendorScripts.html"/>

在 vendorScripts.html 文件中,您可以包含您的脚本参考,如:

<script src="scripts/vendors/jquery.js"></script>
<script src="scripts/vendors/bootstrap.js"></script>
<script src="scripts/vendors/angular.js"></script>
<script src="scripts/vendors/angular-route.js"></script>

查看 HTML Imports 更多详细信息。

不幸的是,它只在Chrome中工作。

使用 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

您只能使用要求();标签。

例如,如果我有一个 addition.js 模块,我想添加到 math.js,我会这样做:

//this is math.js

//vars
let a = 1;
let b = 3;

//start of code
const additionfile = require('addition.js');
window.alert("You added " + a + " and " + b + " together, to get " + additionfile.add(a,b) + "!");

如果你想要添加.js 文件,它会看起来像这样的东西

function add(a,b) {
   const sum = a + b;
   return sum;
}