这与ES6 Modules In Google Chrome Extension Development (unexpected token)的问题不同,因为它已经过时且已经得到解答。
Google发布了一则新闻稿,声称Chrome支持ES6模块。我正在尝试从扩展中加载模块。我可以从普通页面加载模块,但不能从扩展名中加载。
这是html,这是扩展上下文中的页面:
<script src="test.js" type="module"></script>
当我打开页面时,我在控制台中看到以下错误消息:
无法加载模块脚本:服务器使用非JavaScript MIME类型&#34;&#34;进行响应。对每个HTML规范的模块脚本强制执行严格的MIME类型检查。
有没有人有任何建议?这是一个应该向Chrome报告的错误吗?或者它还没有得到支持?我无法找到任何直截了当的解释。
答案 0 :(得分:9)
正如评论中提到的用户wOxxOm所见,请参阅https://crbug.com/738739。
9-18-17更新:https://bugs.chromium.org/p/chromium/issues/detail?id=769012看起来正在修复!
10-19-17更新:https://bugs.chromium.org/p/chromium/issues/detail?id=728377#c18报告为使用chrome 64(目前是金丝雀)
11-13-17更新:最终更新,在Chrome 63中测试,模块现在正在运行。请注意,如果您需要在扩展的后台页面中加载模块,则无法通过manifest.json中的scripts属性执行此操作,而是将页面设置为background.html,并在脚本标记中指定类型模块,这将绕过明显的问题。
答案 1 :(得分: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
加载。