我如何在另一个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;
}