ES6 modules in extensions in Chrome version 61

前端 未结 2 2220
余生分开走
余生分开走 2021-02-20 05:56

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

相关标签:
2条回答
  • 2021-02-20 06:31

    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();
            }
        }
    });
        <script src="./script.js" type="module"></script>

    In short: You load the script content, create a Blob with correct type and load it from a ObjectURL.

    0 讨论(0)
  • 2021-02-20 06:39

    As user wOxxOm mentioned in comments, see https://crbug.com/738739.

    9-18-17 update: https://bugs.chromium.org/p/chromium/issues/detail?id=769012 looks like it is being fixed!

    10-19-17 update: https://bugs.chromium.org/p/chromium/issues/detail?id=728377#c18 reported as working in chrome 64 (currently canary)

    11-13-17 update: final update, testing in Chrome 63, modules are now working. Note that if you need to load a module in the background page of the extension, you cannot do it via scripts property in manifest.json, instead set page to background.html, and specify type module in script tag, and that will bypass the manifest issue.

    0 讨论(0)
提交回复
热议问题