我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
假设您想将 A.js 文件导入到 B.js 文件中。
现在肯定您已将 B.js 链接到 HTML 文件中,然后只需在 B.js 之前将 A.js 链接到 HTML 文件中。
这并不需要一个复杂的答案。
其他回答
如果你想要它在纯粹的JavaScript,你可以使用document.write。
document.write('<script src="myscript.js" type="text/javascript"></script>');
如果您使用 jQuery 图书馆,您可以使用 $.getScript 方法。
$.getScript("another_script.js");
是的,有......
在 ES6 中,我们可以将部分或整个JavaScript文件导出并导入到另一个文件中。
但等待,ES6不支持所有浏览器,所以你需要通过 babel.js 使用它,例如...
所以你创建一个类如下:
class Person {
constructor(name) {
this.name = name;
}
build() {
return new Person(this);
}
}
module.exports = Person;
import { Person } from 'Person';
您也可以要求文件如:
const Person = require('./Person');
如果您正在使用更古老的 JavaScript 版本,您可以使用 requirejs:
requirejs(["helper/util"], function(util) {
// This function is called when scripts/helper/util.js is loaded.
// If util.js calls define(), then this function is not fired until
// util's dependencies have loaded, and the util argument will hold
// the module value for "helper/util".
});
如果你想坚持旧版本的物品,如jQuery,你也可以使用一些东西,如 getScript:
jQuery.getScript('./another-script.js', function() {
// Call back after another-script loaded
});
最后,但不要忘记,你可以用 <script> 标签一起编写脚本的传统方式。
<script src="./first-script.js"></script>
<script src="./second-script.js"></script>
<script src="./third-script.js"></script>
注意: 有几种方式可以执行一个外部脚本: 如果 async 存在: 脚本与页面剩余的同步执行(脚本将执行,而页面继续播放) 如果 async 没有存在,并且 defer 存在: 脚本在页面完成播放时执行 如果没有 async 或 defer 存在: 脚本被捕并执行 imme
您只能使用要求();标签。
例如,如果我有一个 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;
}
另一个方法是使用HTML进口,这些可以包含脚本参考以及风格表参考。
您可以将 HTML 文件链接到
<link rel="import" href="vendorScripts.html"/>
在 vendorScripts.html 文件中,您可以包含您的脚本参考,如:
<script src="scripts/vendors/jquery.js"></script>
<script src="scripts/vendors/bootstrap.js"></script>
<script src="scripts/vendors/angular.js"></script>
<script src="scripts/vendors/angular-route.js"></script>
查看 HTML Imports 更多详细信息。
不幸的是,它只在Chrome中工作。
在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