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


当前回答

我创建了一个功能,它将允许你使用类似于C#/Java的语法,以包含一个JavaScript文件。我已经测试了一点甚至从另一个JavaScript文件的内部,它似乎工作。

我把这个代码放在我的脚本目录的根源文件(我称之为 global.js,但你可以使用你想要的任何东西. 除非我错了这个和jQuery应该是唯一需要的脚本在一个特定的页面上. 请记住,这在很大程度上是未测试的某些基本使用,所以可能或可能没有任何问题与我做了的方式; 使用在自己的风险,我没有责任,如果你 scr

/**
* @fileoverview This file stores global functions that are required by other libraries.
*/

if (typeof(jQuery) === 'undefined') {
    throw 'jQuery is required.';
}

/** Defines the base script directory that all .js files are assumed to be organized under. */
var BASE_DIR = 'js/';

/**
* Loads the specified file, outputting it to the <head> HTMLElement.
*
* This method mimics the use of using in C# or import in Java, allowing
* JavaScript files to "load" other JavaScript files that they depend on
* using a familiar syntax.
*
* This method assumes all scripts are under a directory at the root and will
* append the .js file extension automatically.
*
* @param {string} file A file path to load using C#/Java "dot" syntax.
*
* Example Usage:
* imports('core.utils.extensions');
* This will output: <script type="text/javascript" src="/js/core/utils/extensions.js"></script>
*/
function imports(file) {
    var fileName = file.substr(file.lastIndexOf('.') + 1, file.length);

    // Convert PascalCase name to underscore_separated_name
    var regex = new RegExp(/([A-Z])/g);
    if (regex.test(fileName)) {
        var separated = fileName.replace(regex, ",$1").replace(',', '');
        fileName = separated.replace(/[,]/g, '_');
    }

    // Remove the original JavaScript file name to replace with underscore version
    file = file.substr(0, file.lastIndexOf('.'));

    // Convert the dot syntax to directory syntax to actually load the file
    if (file.indexOf('.') > 0) {
        file = file.replace(/[.]/g, '/');
    }

    var src = BASE_DIR + file + '/' + fileName.toLowerCase() + '.js';
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = src;

    $('head').find('script:last').append(script);
}

其他回答

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

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

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

如果您使用 Angular,那么一个插件模块 $ocLazyLoad 可以帮助您做到这一点。

以下是其文档的一些引用:

加载一个或多个模块和组件有多个文件: $ocLazyLoad.load([‘testModule.js’,‘testModuleCtrl.js’,‘testModuleService.js’]);加载一个或多个模块有多个文件,并在需要时指定一个类型: 注意: 使用需要JS 风格格格格式(例如,从 js! 开始时),不要指定一个文件扩展。

在过去的一项项目中,我很成功地使用ajile进行重复使用的JavaScript文件的进口,我总是希望有一个功能为此建立在JavaScript本身。

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";
}

這裡有一個工作例子。

还有 Head.js. 很容易处理:

head.load("js/jquery.min.js",
          "js/jquery.someplugin.js",
          "js/jquery.someplugin.css", function() {
  alert("Everything is ok!");
});

正如你所看到的,它比 Require.js 更容易,而且像 jQuery 的 $.getScript 方法一样方便,它还有一些先进的功能,如条件加载、功能检测等。