我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
输入声明在 ECMAScript 6 中。
合成
import name from "module-name";
import { member } from "module-name";
import { member as alias } from "module-name";
import { member1 , member2 } from "module-name";
import { member1 , member2 as alias2 , [...] } from "module-name";
import name , { member [ , [...] ] } from "module-name";
import "module-name" as name;
其他回答
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";
}
這裡有一個工作例子。
是的,有......
在 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
若要在 JavaScript 中输入另一个脚本,请使用输入关键字:
import '/src/js/example.js';
// both types of quotes work
import "/src/js/example2.js";
var xxx = require("../lib/your-library.js")
或
import xxx from "../lib/your-library.js" //get default export
import {specificPart} from '../lib/your-library.js' //get named export
import * as _name from '../lib/your-library.js' //get full export to alias _name
var js = document.createElement("script");
js.type = "text/javascript";
js.src = jsFilePath;
document.body.appendChild(js);
推荐文章
- 错误:'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授权头
- 为什么我的球(物体)没有缩小/消失?