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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章