自学内容网 自学内容网

javascript异步动态加载模块,导出和导入代码

异步动态导入模块中的代码是ES6中使用模块化的方法,方便按需加载模块

//这是模块(exportModule.js)有两个函数被导出

const foo=()=>{
    console.log('foo');
};

export {foo as myFoo};

export function add(x,y)
{
    console.log(x+y);
}

//然后在html代码中动态导入并运行

<html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
        <title>测试export模块导出</title>
    </head>
    <body>
        

        <script>
        //异步动态导入模块代码,返回的是期约
            async function loadModule(){
                const f=await import('./exportModule.js');
                
                f.myFoo();
                f.add(5,6);
            }
            loadModule();
           
        </script>
        //这里是模块化导入,用了type=module
        <script type="module">
            import {myFoo,add} from './exportModule.js';
            myFoo();
            add(5,6);
        </script>
        
    </body>
</html>

原文地址:https://blog.csdn.net/cdcdhj/article/details/142992460

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!