美文网首页
es6的导入导出-模块化

es6的导入导出-模块化

作者: coderYJ | 来源:发表于2018-07-04 20:21 被阅读217次

大家都知道es6是ECMAScript的下一代js版本,随着浏览器的更新迭代,主流浏览器逐渐支持es6,那么今天就介绍一下es6的导入导出功能吧
想使用es6的导入导出功能不需要配置nodejs环境和webpack环境,直接可以用
导入导出的功能是模块化,使你的js功能独立,这样有利于你的代码解耦,提高代码的复用性

  • 1.新建js文件写入下列代码
// 使用es6箭头函数定义一个函数
let fn = a=> alert(a);
// 导出函数
export  {fn};
  • 2.新建HTML文件导入这个函数模块
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="box"></div>
<script type="module">
    // 导入这个模块
    import {fn} from "./index1.js"
    // 调用这个模块
    fn(1);
</script>
</body>
</html>

ps:这里说明一下要想使用es6的导入导出模块,必须给导入的script标签设置type类型为module

  • 3.执行HTML文件你会发现有一个弹框


    执行之后会有弹框
  • 4.如果你想在js中导入其他js也是可以的
// 在index2.js中导入index1.js的模块
import {fn} from './index1.js';
function f2() {
// 执行index1的模块
    fn(1);
    alert(2);
}
export  { f2 };
  • 5.外界使用
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="box"></div>
<script type="module">
    import {f2} from "./index2.js"
    f2(1);
</script>
</body>
</html>
  • 6.好了今天的es6语法的导入导出就到这里了

持续更新实用的干货
微信公众号关注coderYJ
简书关注coderYJ
微博关注coderYJ

相关文章

网友评论

      本文标题:es6的导入导出-模块化

      本文链接:https://www.haomeiwen.com/subject/oeyyuftx.html