我如何在另一个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>
推荐文章
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?