模块暴露的三种方式

  1. 分别暴露(m1.js)

    export let roozen = 'roozen.xyz'
    
    export function open(){
        console.log(`m1打开了${roozen}`)
    }
    
  2. 统一暴露(m2.js)

    let roozen = 'www.roozen.xyz'
    
    function open(){
        console.log(`m2打开了${roozen}`)
    }
    
    export {roozen,open}
    
  3. 默认暴露(m3.js)

    export default {
        website:'roozen.xyz',
        open:function (){
            console.log(`m3打开了${this.website}`);
        }
    }
    

模块引入的方式

  1. 在html文件中(index.html)

    <!-- 使用import导入其他模块要加type属性 -->
    <script type="module">
        import * as m from './m1.js'
        m.open();
    </script>
    
  2. 在js文件中(app.js)

    //通用导入
    import * as m1 from './m1.js'
    console.log(m1.roozen);
    m1.open;
    
    //解构形式导入
    import { roozen as otherName,open as otherFunctionName} from './m2.js';
    console.log(otherName)
    otherFunctionName();
    //default的解构导入必须有别名
    import {default as bieMing} from './m3.js'
    console.log(bieMing.website)
    bieMing.open();
    
    //简便导入(只针对默认暴露的模块)
    import m3 from './m3.js'
    console.log(m3.website)
    m3.open();
    

    然后再在html中导入app.js

    <!-- 引入入口js模块 -->
    <script src="./app.js" type="module"></script>
    

注:

Es6模块化开发出现报错 Access to script at 'file:xxx' from origin 'null' has been blocked by CORS policy origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.

解决方法: VScode中安装Live Server 插件

选择Open with Live Server