You don't need npm and bundler.
You need just a service-worker
script.
- Transform
.js
with babel on service-worker - Transform
.ts
and.tsx
with typescript on service-worker - Load modules from jspm.io and cache them on serviceWorker.
- development only. Do not use for production.
- It works only for modern browser(ES2015+ and ES Modules ready).
Put dist/sw.js as /sw.js
on your app root.
wget https://raw.githubusercontent.com/mizchi/trans-loader/master/dist/sw.js
Rewrite your entry js like below.
Before
<script src="/src/main.js"></script>
After
<script type=module>
(async () => {
const run = () => import('/src/main.js') // your entry js
if (navigator.serviceWorker.controller) {
run()
} else {
const reg = await navigator.serviceWorker.register("/sw.js");
await navigator.serviceWorker.ready;
navigator.serviceWorker.addEventListener('controllerchange', run)
}
})()
</script>
See working demo
// /your-entry.js
import React from "react";
import ReactDOM from "react-dom";
ReactDOM.render(<h1>Hello</h1>, document.querySelector(".root"));
index.html
sw.js
src/main.js
src/components/App.js
// main.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
ReactDOM.render(<App />, document.querySelector(".root"));
index.html
sw.js
src/main.js
src/components/App.tsx
// main.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
ReactDOM.render(<App />, document.querySelector(".root"));
index.html
sw.js
package.json
src/main.js
package.json
{
"dependencies": {
"react": "16.4.1",
"react-dom": "16.4.1"
}
}
Log
trans-loader: Cache https://dev.jspm.io/react@16.4.1
trans-loader: Cache https://dev.jspm.io/react-dom@16.4.1
Compile content with babel/typescript by extname
// ...
self.addEventListener("fetch", (event: any) => {
if (event.request.url.indexOf("dev.jspm.io") > -1) {
// cache jspm result
event.respondWith(useCacheOrLoad(event.request));
} else if (event.request.url.indexOf("/src/") > -1) {
// transform
console.log("trans-loader: with-transform", event.request.url);
event.respondWith(respondWithTransform(event.request.url));
}
});
Rewrite npm module path to dev.jspm.io
. See this code
// before
import React from "react";
// after
import React from "https://dev.jspm.io/react";
- Try to access
.js, .mjs, .ts, .tsx, /index.js, /index.ts, /index.tsx
- return file with non-error endpoint
MIT