2017-08-17 101 views
11

這與ES6 Modules In Google Chrome Extension Development (unexpected token)的問題並不相同,因爲它既過時又已回答。Chrome版本61中的擴展模塊中的ES6模塊

谷歌製作了一則新聞稿,聲稱Chrome支持ES6模塊。我正在嘗試從擴展中加載模塊。我能夠從普通頁面內加載模塊,但不能從擴展內部加載模塊。

下面是HTML,這是一個擴展上下文頁:

<script src="test.js" type="module"></script> 

當我打開網頁,我在控制檯看到以下錯誤信息:

無法加載模塊腳本:服務器使用非JavaScript MIME類型的「」進行響應。每個HTML規範的模塊腳本都會執行嚴格的MIME類型檢查。

有沒有人有任何建議?這是一個應該向Chrome報告的錯誤嗎?或者它還沒有被支持?我找不到任何直截了當的解釋。

+0

這是在Mac上。該文件是從擴展內部本地加載的。該URL類似於chrome://extensionid/test/test.html – Josh

+1

我認爲它最終會成爲chrome擴展的問題,它們可能需要關閉對本地資源的mime類型檢查,並假定默認的MIME類型爲腳本資源與一個有效的js之一。說我會想,現在還很早。 – MinusFour

+1

尚未支持,請訪問https://crbug.com/738739 – wOxxOm

回答

7

作爲用戶wOxxOm在評論中提到,請參閱https://crbug.com/738739

9-18-17更新:https://bugs.chromium.org/p/chromium/issues/detail?id=769012看起來像它正在修復!

17年10月19日更新:https://bugs.chromium.org/p/chromium/issues/detail?id=728377#c18報告爲在鉻64(目前金絲雀)

17年11月13日更新的工作:最後的更新,在鉻63的測試,模塊現在正在。請注意,如果您需要在擴展的後臺頁面中加載模塊,則無法通過manifest.json中的scripts屬性執行此操作,而是將頁面設置爲background.html,並在腳本標記中指定類型模塊,並且將繞過明顯的問題。

+0

不幸的是有另一個錯誤報告在那裏...無論如何這是有趣的,但讓我認爲es6模塊將需要翻譯至少一年的鉻擴展:/ – YangombiUmpakati

0

這可能是一個加載本地文件的錯誤。 我設法創建一個解決辦法,但你還是會得到一個錯誤的控制檯,您不能使用原產地問題內到期的其他import語句我想:

window.addEventListener('load', function() { 
 
    function appendModule(code) { 
 
     let url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' })); // create url from code 
 

 
     let script = document.createElement('script'); 
 
     script.type = 'module'; 
 
     script.src = url; 
 
     document.head.appendChild(script); 
 
    } 
 

 
    let scripts = document.querySelectorAll('script'); 
 
    console.log(scripts); 
 
    for (let script of scripts) { 
 
     script.parentElement.removeChild(script); 
 
     if (script.getAttribute('type') !== 'module') continue; // found normal script 
 
     if (script.getAttribute('src') !== null) { 
 
      // load a file 
 
      var request = new XMLHttpRequest(); 
 
      request.open('GET', script.getAttribute('src') + '?_=' + Date.now(), true); 
 
      request.onload = function() { 
 
       if (this.status >= 200 && this.status < 400) { 
 
        // file loaded 
 
        appendModule(this.response); 
 
       } else { 
 
        // error loading file 
 
        console.error('Not able to load module:', script.getAttribute('src')); 
 
       } 
 
      }; 
 
      request.onerror = function() { 
 
       // error loading file 
 
       console.error('Not able to load module:', script.getAttribute('src')); 
 
      }; 
 
      request.send(); 
 
     } 
 
    } 
 
});
<script src="./script.js" type="module"></script>

在簡而言之:您加載腳本內容,使用正確的類型創建Blob,並從ObjectURL加載它。