JS中ES6的模块化

原生支持模块化了

ES6中新增的模块化,即从ES6开始,原生js支持模块化了,现在很多浏览器也支持模块化了。

  1. 模块化的两个概念
    1. 导出(export关键字):导出就是对外开放的,可以导出变量,常量,函数,对象等等。使用export关键字。放在export关键字后面的(即对外导出的)变量,常量,函数和对象,在其它js文件中可以使用,否则,其它js文件中是不能使用的。即只能内部使用的。

           在用export导出时,可以导出多个

           如:person.js文件(模块)里,如下:

//导出字符串
export var str = "hello";
//导出函数
export var fun = function(){
    alert("我是函数");
}
//导出对象
export const p =  {
    "id":"007",
    "name":"张三疯",
    "eat":function(){
        alert("吃");
        ff();
    }
}
//此函数没有使用export关键字导出,所以,只能在当前js文件内部使用
function ff(){
    alert("我只能在当前js被使用");
}

 

2.导入(import):导入就是把其它js文件引入到当前js文件里。使用关键字import。

在使用import导入(export导出的)时,要使用花括号,

如:import {str,fun,p} from './person.js';


在index.js文件中,引入模块person.js;

//导入时,需要使用{},这是解构赋值。
import {str,fun,p} from './person.js';

window.onload = function(){
    document.getElementById("btn01").onclick = function(){
        console.log(str);
        fun();
        console.log(p.id);
        p.eat();
    }
}
      1. 在html文件中引入index.js(注意: type="module")
        注意:js中使用了模块化的关键字import,在引入时,script标签的type属性的值必须写成module。即:<script type="module" src="js/index.js"></script>
<body>
    <input id="btn01" type="button" value="测试" />
</body>
<script type="module" src="js/index.js"></script>

注意:测试以上代码时,google浏览器要求放在服务器上进行 ,否则,就会有跨域问题。

 

    1. export defaultexport 有什么区别:

 

  1. export与export default均可用于导出常量、函数、文件、模块等
  2. 在一个文件或模块中,export可以有多个,export default仅有一个,而且export default在导出是不需要变量名,相当于匿名的。
  3. 通过export方式导出,在导入时要加{ },export default则不需要

 

代码示例:

模块定义:dog.js

export default {
    "name":"大黄",
    "eat":function(){
        alert("吃");
    }
}

导入模块:

import d from './dog.js';
window.onload = function(){
    document.getElementById("btn01").onclick = function(){
        console.log(d);
        d.eat();
    }
}
发布了9 篇原创文章 · 获赞 2 · 访问量 269

猜你喜欢

转载自blog.csdn.net/xuhua32100/article/details/103880109