JavaScript中有没有类似于CSS中的@import的东西,允许您将一个JavaScript文件包含在另一个JavaScript文件中?

推荐答案

旧版本的JavaScript没有导入,没有包含,也没有要求,所以已经开发了许多不同的方法来解决这个问题.

但自2015年(ES6)以来,JavaScript已经有了在Node中导入模块的ES6 modules个标准.js,most modern browsers也支持它.

为了与旧浏览器兼容,可以使用WebpackRollup等构建工具和/或Babel等透明工具.

ES6 Modules

自v8以来,ECMAScript(ES6)模块已经有supported in Node.js个.5、带--experimental-modules标志,且自至少 node .js v13.8.0没有国旗.要启用"ESM"(与Node.js以前的CommonJS样式模块系统["CJS"]),您可以在package.json中使用"type": "module",或者将文件的扩展名设为.mjs.(类似地,如果默认为ESM,则使用Node.js以前的CJS模块编写的模块可以命名为.cjs.)

使用package.json:

{
    "type": "module"
}

然后module.js:

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

然后main.js:

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

使用.mjs,您将得到module.mjs:

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

然后main.mjs:

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

浏览器中的ECMAScript模块

浏览器已经支持直接加载ECMAScript模块(不需要webpack这样的工具)sinceSafari10.1、Chrome61、Firefox60和Edge16.不需要使用Node.js的.mjs扩展名;浏览器完全忽略模块/脚本上的文件扩展名.

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

阅读https://jakearchibald.com/2017/es-modules-in-browsers/页的更多内容

浏览器中的动态导入

动态导入允许脚本根据需要加载其他脚本:

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

阅读https://developers.google.com/web/updates/2017/11/dynamic-import页的更多内容

Node.js require

较旧的CJS模块样式,仍广泛用于Node.js是module.exports/require系统.

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

JavaScript还有其他方法可以在不需要预处理的浏览器中包含外部JavaScript内容.

AJAX Loading

您可以通过AJAX调用加载一个额外的脚本,然后使用eval来运行它.这是最简单的方法,但由于JavaScriptSandbox 安全模型,它仅限于您的域.使用eval还打开了漏洞、黑客和安全问题的大门.

Fetch Loading

与动态导入一样,您可以通过fetch调用加载一个或多个脚本,使用Fetch Inject库控制脚本依赖项的执行顺序:

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 Loading

jQuery库提供加载功能in one line:

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

Dynamic Script Loading

您可以将带有脚本URL的脚本标记添加到HTML中.为了避免jQuery的开销,这是一个理想的解决方案.

该脚本甚至可以驻留在不同的服务器上.此外,浏览器还判断代码.可以将<script>标签注入网页<head>,或者恰好在结束</body>标签之前插入.

下面是一个如何工作的示例:

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)
}

此函数将在页面的Head部分的末尾添加一个新的<script>标记,其中src属性设置为作为第一个参数提供给函数的URL.

这两种解决方案都在JavaScript Madness: Dynamic Script Loading中进行了讨论和说明.

Detecting when the script has been executed

现在,有一个大问题你必须知道.这样做意味着you remotely load the code美元.现代Web浏览器将加载文件并继续执行当前脚本,因为它们异步加载所有内容以提高性能.(这既适用于jQuery方法,也适用于手动动态脚本加载方法.)

这意味着如果你直接使用这些技巧,you won't be able to use your newly loaded code the next line after you asked it to be loaded,因为它仍将加载.

例如:my_lovely_script.js包含MySuperObject:

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

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

document.body.appendChild(js);

var s = new MySuperObject();

Error : MySuperObject is undefined

然后点击F5重新加载页面.而且很有效!令人困惑

So what to do about it ?

你可以使用作者在我给你的链接中建议的黑客攻击.总之,对于匆忙的人,他在加载脚本时使用事件来运行回调函数.因此,可以使用远程库将所有代码放入回调函数中.例如:

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 function中后,编写要使用的代码:

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

然后你运行所有这些:

loadScript("my_lovely_script.js", myPrettyCode);

请注意,该脚本可能在加载DOM之后或之前执行,具体取决于浏览器以及您是否包含第script.async = false;行.有great article on Javascript loading in general分讨论这个.

Source Code Merge/Preprocessing

正如本答案顶部所提到的,许多开发人员在他们的项目中使用构建/转换工具,如Parcel、webpack或Babel,允许他们使用即将到来的JavaScript语法,提供对旧浏览器的向后兼容性,合并文件,缩小,执行代码拆分等.

Javascript相关问答推荐

深嵌套的ng-container元素仍然可以在Angular 布局组件中正确渲染内容吗?

扫描qr code后出错whatter—web.js

Msgraph用户邀请自定义邮箱模板

更改JSON中使用AJAX返回的图像的路径

Websocket错误—有一个或多个保留位开启:reserved1 = 1,reserved2 = 0,reserved3 = 0

用JS从平面文件构建树形 struct 的JSON

NG/Express API路由处理程序停止工作

将异步回调转换为异步生成器模式

TypeError:无法读取未定义的属性(正在读取';宽度';)

AJAX POST在控制器中返回空(ASP.NET MVC)

为什么在函数中添加粒子的速率大于删除粒子的速率?

为什么我不能使用其同级元素调用和更新子元素?

我无法在Api Reaction本机上发出GET请求

脚本语法错误只是一个字符串,而不是一个对象?

如何在Java脚本中添加一个可以在另一个面板中垂直调整大小的面板?

单击时同时 Select 和展开可访问的行

鼠标进入,每秒将图像大小减小5%

查找函数句柄的模块/文件

动画可以在Chrome上运行,但不能在Safari上运行

Chart.js根据 Select 显示数据