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


当前回答

保持它好,短,简单,可持续的! :]

// Third-party plugins / script (don't forget the full path is necessary)
var FULL_PATH = '', s =
[
    FULL_PATH + 'plugins/script.js'      // Script example
    FULL_PATH + 'plugins/jquery.1.2.js', // jQuery Library
    FULL_PATH + 'plugins/crypto-js/hmac-sha1.js',      // CryptoJS
    FULL_PATH + 'plugins/crypto-js/enc-base64-min.js'  // CryptoJS
];

function load(url)
{
    var ajax = new XMLHttpRequest();
    ajax.open('GET', url, false);
    ajax.onreadystatechange = function ()
    {
        var script = ajax.response || ajax.responseText;
        if (ajax.readyState === 4)
        {
            switch(ajax.status)
            {
                case 200:
                    eval.apply( window, [script] );
                    console.log("library loaded: ", url);
                    break;
                default:
                    console.log("ERROR: library not loaded: ", url);
            }
        }
    };
    ajax.send(null);
}

// Initialize a single load
load('plugins/script.js');

// Initialize a full load of scripts
if (s.length > 0)
{
    for (i = 0; i < s.length; i++)
    {
        load(s[i]);
    }
}

这个代码只是一个短暂的功能例子,可能需要额外的功能功能,以便在任何(或提供)平台上提供完整的支持。

其他回答

输入声明在 ECMAScript 6 中。

合成

import name from "module-name";
import { member } from "module-name";
import { member as alias } from "module-name";
import { member1 , member2 } from "module-name";
import { member1 , member2 as alias2 , [...] } from "module-name";
import name , { member [ , [...] ] } from "module-name";
import "module-name" as name;

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

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

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

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

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

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

我创建了一个功能,它将允许你使用类似于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);
}
var xxx = require("../lib/your-library.js")

import xxx from "../lib/your-library.js" //get default export
import {specificPart} from '../lib/your-library.js' //get named export
import * as _name from '../lib/your-library.js'  //get full export to alias _name