博客列表 >ES6 模块知识入门

ES6 模块知识入门

不露声色
不露声色原创
2021年04月13日 09:20:13586浏览

关于模块

  • 2021-4-12

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>Document</title>
    8. </head>
    9. <body>
    10. <!-- 注意这里的type 必须带上,否则会报Uncaught SyntaxError: Cannot use import statement outside a module 的致命错误-->
    11. <script type="module">
    12. //这里如果是引用默认的模块不需要加上小夸号
    13. import hello , { userName , User } from "./module1.js";
    14. console.log(userName);
    15. console.log(hello("assd"));
    16. let a = new User("asdasdd",999);
    17. a.print();
    18. //控制台输出结果如下
    19. </script>
    20. </body>
    21. </html>

  1. //module1.js
  2. //关于模块知识
  3. let userName = "pandacode";
  4. function hello(name){
  5. return "hello" + name;
  6. }
  7. class User
  8. {
  9. //构造函数
  10. constructor(product,price){
  11. this.product = product;
  12. this.price = price;
  13. }
  14. //函数输出
  15. print(){
  16. console.log(this.product + this.price);
  17. }
  18. }
  19. //模块可以对变量函数类进行导出
  20. //但仅允许导出一个默认模块
  21. export { userName , User , hello as default}
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <script type="module">
  11. //如果使用命名空间,我们可以先看下这个对象
  12. //此时默认模块的hello 被default代替
  13. import * as namespace from "./module1.js";
  14. console.log(namespace);
  15. // import hello , { userName , User } from "./module1.js";
  16. console.log(namespace.userName);
  17. console.log(namespace.default("assd"));
  18. let a = new namespace.User("asdasdd",999);
  19. a.print();
  20. </script>
  21. </body>
  22. </html>

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议