我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
您只能使用要求();标签。
例如,如果我有一个 addition.js 模块,我想添加到 math.js,我会这样做:
//this is math.js
//vars
let a = 1;
let b = 3;
//start of code
const additionfile = require('addition.js');
window.alert("You added " + a + " and " + b + " together, to get " + additionfile.add(a,b) + "!");
如果你想要添加.js 文件,它会看起来像这样的东西
function add(a,b) {
const sum = a + b;
return sum;
}
其他回答
这就是简单的:
var js = document.createElement("script");
js.type = "text/javascript";
js.src = jsFilePath;
document.body.appendChild(js);
ES6 模块
是的,在脚本标签(支持)中使用 type="module" :
<script type="module" src="script.js"></script>
在一个 script.js 文件中包含另一个文件如下:
import { hello } from './module.js';
...
// alert(hello());
在“module.js”中,您必须导出您将导入的函数/类:
export function hello() {
return "Hello World";
}
這裡有一個工作例子。
做一个小提问,并评估结果。
从.mix 文件中的混合文档:
混合文件只是.js 或.css 文件与.mix. 在文件名中. 混合文件只是扩展正常风格或脚本文件的功能,并允许您进口和结合。
以下是一個.mix 檔案的例子,將多個.js 檔案組成一個:
// scripts-global.mix.js
// Plugins - Global
@import "global-plugins/headroom.js";
@import "global-plugins/retina-1.1.0.js";
@import "global-plugins/isotope.js";
@import "global-plugins/jquery.fitvids.js";
混合输出这个作为脚本-global.js 以及作为一个小型版本(脚本-global.min.js)。
注意:我不以任何方式与混合,除了使用它作为一个前端开发工具. 我遇到了这个问题,看到一个混合JavaScript文件在行动(在一个混合板)并有点混淆它(“你可以这样做吗?”我认为自己)。 然后我意识到这是一个应用程序特定的文件类型(有些令人失望,同意)。
您只能使用要求();标签。
例如,如果我有一个 addition.js 模块,我想添加到 math.js,我会这样做:
//this is math.js
//vars
let a = 1;
let b = 3;
//start of code
const additionfile = require('addition.js');
window.alert("You added " + a + " and " + b + " together, to get " + additionfile.add(a,b) + "!");
如果你想要添加.js 文件,它会看起来像这样的东西
function add(a,b) {
const sum = a + b;
return sum;
}
推荐文章
- 错误:'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授权头
- 为什么我的球(物体)没有缩小/消失?