javascript~引用js的module


我們知道,在script標簽中寫js代碼,或者使用src引入js文件時,默認不能使用module形式,即不能使用import導入文件,但是我們可以再script標簽上加上type=module屬性來改變方式。

  • 使用方法如下:
  • js引用js
    //module.js
    export default function test(){
      return 'test...'
    }

    // index.js
    import test from './module.js';
    console.log(test())
  • html頁面引用js
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
      // 方法 1 : 引入module.js,然后在script標簽里面調用
      <script type="module">
        import test from './module.js';
        console.log(test())
      </script>
     
      // 方法 2 : 直接引入index.js,使用src引入
      <script type="module" src="./index.js"></script>
     
    </body>
    </html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM