Skip to content

Instantly share code, notes, and snippets.

@zak905
Created November 5, 2017 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zak905/8ce23504526ec09df1789f0f93afd13a to your computer and use it in GitHub Desktop.
Save zak905/8ce23504526ec09df1789f0f93afd13a to your computer and use it in GitHub Desktop.
Script to automatically generate service worker after a GWT build and before packaging the app.
{
"name": "gwt-pwa",
"version": "0.0.1",
"description": "generates service worker for GWT app",
"main": "serviceWorkerBuilder.js",
"dependencies": {
"handlebars": "^4.0.11"
},
"devDependencies": {},
"scripts": {
"generate": "node serviceWorkerBuilder.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/zak905/gwt-pwa-demo.git"
},
"author": "zakaria amine",
"license": "ISC",
"bugs": {
"url": "https://github.com/zak905/gwt-pwa-demo/issues"
},
"homepage": "https://github.com/zak905/gwt-pwa-demo#readme"
}
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>npm install</id>
<goals>
<goal>npm</goal>
</goals>
<phase>generate-resources</phase>
<configuration>
<arguments>install</arguments>
</configuration>
</execution>
<execution>
<id>npm generate</id>
<goals>
<goal>npm</goal>
</goals>
<phase>prepare-package</phase>
<configuration>
<arguments>run-script generate ${project.build.finalName}</arguments>
</configuration>
</execution>
</executions>
</plugin>
const args = process.argv;
const arguments = args.slice(2);
const buildFolderName = arguments[0];
const gwtModuleName = arguments[1];
if (typeof buildFolderName === 'undefined' || !buildFolderName){
console.log("please provide the name of the build folder");
return;
}
const rootFolder = 'target/' + buildFolderName;
const fs = require('fs');
var Handlebars = require('handlebars');
var filesToCache = [];
browseAllFilesInDirectory(rootFolder);
function browseAllFilesInDirectory(folder) {
const filesRegExp = /\.(html|css|js|gif|png|jpeg)$/i;
const exceptions = ["WEB-INF", "META-INF", "bower_components", "clear.cache.gif"];
fs.readdirSync(folder).forEach(fileName => {
const resource = folder + "/" + fileName;
if (exceptions.indexOf(fileName) < 0) {
if (fileName.match(filesRegExp)) {
filesToCache.push(resource.replace(rootFolder+"/", ""));
} else if (fs.lstatSync(resource).isDirectory()) {
browseAllFilesInDirectory(resource);
}
}
});
}
var swData = {
cacheName: gwtModuleName || "cache_"+new Date().getTime().toString(),
filesToCache: filesToCache,
};
fs.readFile("sw_template.js", "utf8", (error, data) => {
if (error) {
console.log("Unable to read template file");
}
var template = Handlebars.compile(data);
var serviceWorkerJs = template(swData);
fs.writeFile(rootFolder+"/sw.js", serviceWorkerJs, (error) => {
console.log("successfully generated service worker sw.js in " + rootFolder);
});
});
var cacheName = '{{cacheName}}';
var filesToCache = [ {{#each filesToCache}}
'{{.}}'{{#unless @last}},{{/unless}}
{{/each}}
];
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(cacheName).then(function(cache) {
console.log('[ServiceWorker] Caching app shell');
return cache.addAll(filesToCache);
})
);
});
self.addEventListener('activate', function(e) {
console.log('[ServiceWorker] Activate');
e.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
console.log('[ServiceWorker] Removing old cache', key);
if (key !== cacheName) {
return caches.delete(key);
}
}));
})
);
});
self.addEventListener('fetch', function(e) {
console.log('[ServiceWorker] Fetch', e.request.url);
e.respondWith(
caches.match(e.request).then(function(response) {
return response || fetch(e.request);
})
);
});
@kevzlou7979
Copy link

Hey there this is great but I have some issue on the code itself.
screenshot from 2017-11-06 17-25-58
screenshot from 2017-11-06 17-26-09

@kevzlou7979
Copy link

Also when trying to install my app I got this issue.

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:17 min
[INFO] Finished at: 2017-11-06T17:29:46+08:00
[INFO] Final Memory: 29M/501M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.github.eirslett:frontend-maven-plugin:1.6:npm (npm install) on project gwt-material-demo: Failed to run task: 'npm install' failed. java.io.IOException: Cannot run program "/home/mark/Documents/github/gwt-material-demo/node/node" (in directory "/home/mark/Documents/github/gwt-material-demo"): error=2, No such file or directory -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following 

@zak905
Copy link
Author

zak905 commented Nov 11, 2017

Hey kevzlou7979,

sorry for the late reply. The error seems familiar. What maven goal are you running? It works for me using mvn package. Also, the frontend-maven-plugin does not look for node path in your system, but inside /nodes_modules, so in case you tried to avoid the install-node-and-npm , this may cause it. I did not find enough flexibility in the frontend-maven-plugin to allow using the already installed npm and node. If you find a better way, please let me know. As for the code, I think this might be some misinterpretation from IntelliJ, the code works well if you try node serviceWorkerBuilder.js. Here is the full demo project: https://github.com/gwidgets/gwt-pwa-demo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment