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


当前回答

import "./path/to/js/file";

是的! OP 提出了一些类似于“@import in CSS”的要求,这正是这样。 它也不是像火箭科学复杂的一些旧方法一样。 至少毫无疑问是最初学友好的方法,但我确信非初学者也喜欢它。

要开始使用 Vite for a vanilla JavaScript 项目,只需安装 Node.js 和 [NPM3,然后做:

npm create vite@latest <your-vanilla-js-app-name> --template vanilla

是G:

npm create vite@latest my-js-app --template vanilla

正如一个侧面注意事项: 还有另一个可能在你的脑海中出现的问题是名称空间问题,例如,如果你在你所包含的文件中使用的名称类似于你已经在当前文件中的名称吗? 但这是JavaScript的性质,对吗? 这不是这个方法的具体问题。

其他回答

从丹·达斯卡莱斯库(Dan Dascalescu)的答案,从Facebook的想法中获取了一些图书馆的扩展。

(function() {
var __ = {};
this._ = function(name, callback) {
    if(__[name]==undefined) {
        __[name] = true;
        var firstScript = document.getElementsByTagName('script')[0],
          js = document.createElement('script');
          js.src =  name;
          js.onload = callback;
          firstScript.parentNode.insertBefore(js, firstScript);
    }
}
})();

(new _('https://cdnjs.cloudflare.com/ajax/libs/Snowstorm/20131208/snowstorm-min.js', function() {
 snowStorm.snowColor = '#99ccff';
}));

输入声明在 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;

我创建了一个功能,它将允许你使用类似于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);
}

旧版本的JavaScript没有进口,包括,或要求,所以许多不同的方法对这个问题已经开发。

使用 package.json:

{
    "type": "module"
}

export function hello() {
  return "Hello";
}

import { hello } from './module.js';
let val = hello();  // val is "Hello";

export function hello() {
  return "Hello";
}

此分類上一篇:mjs:

import { hello } from './module.mjs';
let val = hello();  // val is "Hello";

ECMAScript 在浏览器中的模块

<script type="module">
  import { hello } from './hello.mjs'; // Or the extension could be just `.js`
  hello('world');
</script>
// hello.mjs -- or the extension could be just `.js`
export function hello(text) {
  const div = document.createElement('div');
  div.textContent = `Hello ${text}`;
  document.body.appendChild(div);
}

在浏览器中的动态进口

<script type="module">
  import('hello.mjs').then(module => {
      module.hello('world');
    });
</script>

Node.js 需要

// mymodule.js
module.exports = {
   hello: function() {
      return "Hello";
   }
}
// server.js
const myModule = require('./mymodule');
let val = myModule.hello(); // val is "Hello"   

您可以使用 AJAX 通话加载额外的脚本,然后使用 eval 运行它. 这是最简单的方式,但由于 JavaScript Sandbox 安全模式而仅限于您的域名。

fetchInject([
  'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js'
]).then(() => {
  console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)
})

jQuery 图书馆在一个行中提供充电功能:

$.getScript("my_lovely_script.js", function() {
   alert("Script loaded but not necessarily executed.");
});

下面是如何工作的例子:

function dynamicallyLoadScript(url) {
    var script = document.createElement("script");  // create a script DOM node
    script.src = url;  // set its src to the provided URL
   
    document.head.appendChild(script);  // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead)
}

var js = document.createElement("script");

js.type = "text/javascript";
js.src = jsFilePath;

document.body.appendChild(js);

var s = new MySuperObject();

Error : MySuperObject is undefined

function loadScript(url, callback)
{
    // Adding the script tag to the head as suggested before
    var head = document.head;
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}

然后,你写下你想要使用的代码后,脚本被加载到一个Lambda函数:

var myPrettyCode = function() {
   // Here, do whatever you want
};

loadScript("my_lovely_script.js", myPrettyCode);

请注意,在 DOM 已加载后,脚本可以运行,或者在此之前,取决于浏览器,以及您是否包含了行 script.async = false;. 有一个关于JavaScript 加载的一般文章,讨论了这一点。

源代码合并/预处理

如果您正在使用 Web 工作者,并希望在工作者的范围内添加额外的脚本,则其他关于添加脚本到标签标签等的答案不会为您工作。

幸运的是,网页工作者有自己的 importScripts 功能,这是在网页工作者的范围内的全球功能,原生于浏览器本身,因为它是规格的一部分。

否则,因为第二个最高的投票答案突出你的问题,RequireJS也可以处理包括在WebWorker内部的脚本(可能称之为ImportScripts本身,但有几个其他有用的功能)。