Stefan Ramson
Stefan Ramson

Reputation: 541

Use browser.js in a service worker

We want to use a Service Worker to perform client-side source code transformation for development purposes. We want to use Babel to transpile ES6+/ES2015 files to ES5 modules.

However, including the browser version of babel in a Service Worker using importScripts causes the following errors:

GET http://localhost:8080/babel-core/browser.js net::ERR_FAILED

Uncaught NetworkError: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'http://localhost:8080/babel-core/browser.js' failed to load.

So, the question is, how to correctly import babel into a Service Worker.

edit: This is not the obvious NetworkError, as we can change the content of the file into something simple, which enables us to actually load and execute the file. Also, the file can be loaded with a normal <script> tag.

edit2: To get this message, check out this repository https://github.com/onsetsu/lively4-core.git, start a local server at port 8080 and finally load http://localhost:8080/bootworker.html. We are currently using Chrome 44.

Upvotes: 3

Views: 1331

Answers (2)

gleb bahmutov
gleb bahmutov

Reputation: 1919

How about my experiment here https://github.com/bahmutov/babel-service - you can see the demo at https://babel-service-demo.herokuapp.com/.

I am using feature tests to detect supported features and transpile the intercepted code selectively. Of course this is just a start and only maps default parameters to babel plugins, but more features could be mapped.

Also, the people behind feature tests are discussing the selective transpile https://github.com/getify/es-feature-tests/issues/9

Upvotes: 3

Jeff Posnick
Jeff Posnick

Reputation: 56144

As a general rule, using a service worker for something crucial for a site's functionality isn't a recommended practice. Service workers are intended to be a progressive enhancement, and your sites should be designed to still be functional if the associated service worker isn't available.

Even in browsers which support service workers, there might not be one controlling your page if a user shift-reloads or if it's the very first navigation, before the service worker has had a chance to take control.

To answer your specific question, the ServiceWorkerGlobalScope under which service worker code executes exposes different functionality vs. a normal page's global scope, and it would appear that something in the browser.js script you're trying to import assumes functionality that's only available in a normal page. Unfortunately, Chrome's DevTools, even with the debugger enabled, doesn't reveal which specific statement is causing the error, so I can't say which exact statement(s) are invalid.

Upvotes: 2

Related Questions