This is not the same question as ES6 Modules In Google Chrome Extension Development (unexpected token) as that is both outdated and already answered.
Google produced a n
It could be a bug with loading local files. I managed to create a workaround for that, but you will still get an error in the console and you can not use other import statements within due to origin issues I guess:
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();
}
}
});
In short: You load the script content, create a Blob
with correct type and load it from a ObjectURL
.