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


当前回答

下面是使用HTML导入的浏览器(而不是Node.js)。

首先,所有 JavaScript 类和脚本都不是.js 文件,而是.js.html 文件(.js.html 只是在 HTML 页面和完整的 JavaScript 脚本/类之间识别),在 <script> 标签中,如下:

MyClass.js.html 的内容:

<script>
   class MyClass {

      // Your code here..

   }

</script>

然后,如果你想进口你的班级,你只需要使用HTML进口:

<link rel="import" href="relative/path/to/MyClass.js.html"/>

<script>
   var myClass = new MyClass();
   // Your code here..
</script>

此分類上一篇: HTML 輸入將減少

HTML 进口减少,有利于 ES6 模块,您应该使用 ES6 模块。

其他回答

我只是写了这个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.

我基本上做如下,创建一个新的元素,并添加它来主导:

var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);

在 jQuery 中:

// jQuery
$.getScript('/path/to/imported/script.js', function()
{
    // Script is now loaded and executed.
    // Put your dependent JavaScript code here.
});

另一种方式,在我看来是更清洁的,是做一个同步的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(); 

或者,而不是按时包含,请在上传之前使用脚本进行编辑。

我使用Sprockets(我不知道是否有其他人)。您将您的JavaScript代码建立在单独的文件中,并包含由Sprockets引擎处理的评论。

也看:

引入Sprockets:JavaScript依赖管理和折磨

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