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


当前回答

在JavaScript中实施模块有几种方式,这里有两个最受欢迎的方式:

ES6 模块

浏览器还不支持这个模块化系统,所以为了你使用这个合成,你必须使用一个包装,如Webpack. 使用一个包装是更好的,因为这可以将所有的不同的文件融入一个单一(或一对相关的)文件。

// main.js file

export function add (a, b) {
  return a + b;
}

export default function multiply (a, b) {
  return a * b;
}


// test.js file

import {add}, multiply from './main';   // For named exports between curly braces {export1, export2}
                                        // For default exports without {}

console.log(multiply(2, 2));  // logs 4

console.log(add(1, 2));  // logs 3

CommonJS(在 Node.js 中使用)

这个模块化系统在 Node.js 中使用,你基本上将你的出口添加到一个被称为 module.exports 的对象,然后你可以通过一个要求(‘modulePath’)访问这个对象。

// main.js file

function add (a, b) {
  return a + b;
}

module.exports = add;  // Here we add our 'add' function to the exports object


// test.js file

const add = require('./main');

console.log(add(1,2));  // logs 3

其他回答

下面是使用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 模块。

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

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

document.body.appendChild(js);

可以动态地创建一个JavaScript标签并将其添加到来自其他JavaScript代码的HTML文档中,这将加载针对JavaScript文件。

function includeJs(jsFilePath) {
    var js = document.createElement("script");

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

    document.body.appendChild(js);
}

includeJs("/path/to/some/file.js");

有一个好消息给你. 很快你将能够轻松地加载JavaScript代码. 它将成为进口JavaScript代码的标准方式,并将是核心JavaScript本身的一部分。

您只需要从“cond.js”中输入代码;从“cond.js”文件中加载一个名为 macro 的代码。

因此,您不需要依靠任何JavaScript框架,也不需要明确进行Ajax通话。

提到:

静态模块分辨率模块充电器

如果您打算上传 JavaScript 文件使用所引入/包含的文件中的功能,您也可以定义全球对象,并将功能定义为对象项目。

世界.js

A = {};

文件1JS

A.func1 = function() {
  console.log("func1");
}

文件2JS

A.func2 = function() {
  console.log("func2");
}

主.js

A.func1();
A.func2();

您只需在 HTML 文件中包含脚本时要小心,命令应该如下:

<head>
  <script type="text/javascript" src="global.js"></script>
  <script type="text/javascript" src="file1.js"></script>
  <script type="text/javascript" src="file2.js"></script>
  <script type="text/javascript" src="main.js"></script>
</head>