Skip to content

Commit

Permalink
add autorequire option (#2)
Browse files Browse the repository at this point in the history
* add autorequire option

* small fixes

* update changelog
  • Loading branch information
denar90 committed Aug 5, 2016
1 parent 5067c58 commit 105737a
Show file tree
Hide file tree
Showing 5 changed files with 138 additions and 10 deletions.
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# Change Log
All notable changes to this project will be documented in this file.
## [1.2.0] - 2016-08-05
### Added
- added autorequire option

## [1.1.0] - 2016-07-29
### Changed
Expand All @@ -9,4 +12,5 @@ All notable changes to this project will be documented in this file.
## 1.0.0 - 2016-07-29
* Initial release

[1.1.0]: https://github.com/denar90/sw-precache-brunch/compare/v1.0.0...v1.1.0
[1.1.0]: https://github.com/denar90/sw-precache-brunch/compare/v1.0.0...v1.1.0
[1.2.0]: https://github.com/denar90/sw-precache-brunch/compare/v1.1.0...v1.2.0
29 changes: 28 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,31 @@ Filename for service worker.
*Default:* `'sw.js'`


##### autorequire [Boolean, Array]

This option gives possibility to add and register
service worker into `html` asset files.
> If value set as `true` service worker will be added and registered to ALL `html` assets automatically.
Config example:

```js
swPrecache: {
'swFileName': 'service-worker.js',
'autorequire': true
}
```

```js
swPrecache: {
'autorequire': ['index.html']
}
```

*Default:* `false`


##### options [Object]

Options for `sw-precache`.
Expand All @@ -28,11 +53,13 @@ Look at all `sw-precache` available [options](https://github.com/GoogleChrome/sw

*Default:* `{staticFileGlobs: ['public/**/*.*']}`


> If you don't pass any configuration properties it will cache all files in your `public` folder and create `sw.js`.
All what you need is [register service worker](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration) for your app.


###Config example
```javascript
```js

module.exports = {
files: {
Expand Down
58 changes: 54 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
const swPrecache = require('sw-precache');
const sysPath = require('path');
const defaultSWOptions = {staticFileGlobs: []};
const fs = require('fs');
const async = require('async');
const cheerio = require('cheerio');
let swFileName = 'sw.js';

class SWCompiler {
Expand All @@ -16,14 +19,61 @@ class SWCompiler {
const publicPath = cfg.paths.public;
const config = cfg.plugins && cfg.plugins.swPrecache;

swFileName = config.swFileName || swFileName;

this.swFilePath = sysPath.join(publicPath, swFileName);
this.swFileName = config.swFileName || swFileName;
this.swFilePath = sysPath.join(publicPath, this.swFileName);
this.autorequire = (Array.isArray(config.autorequire) || config.autorequire === true) ? config.autorequire : false;
this.options = config.options || defaultSWOptions;

if (!this.options.staticFileGlobs.length) this.options.staticFileGlobs.push(`${publicPath}/**/*.*`);
}

onCompile() {
_getAssetsList(originalAssets) {
originalAssets = originalAssets.map((data) => {
return data.destinationPath;
});

return Array.isArray(this.autorequire) ? this.autorequire : originalAssets;
}

_includeSWIntoAsset(assetsList) {
async.each(assetsList, this._openFile.bind(this));
}

_openFile(file, cb) {
fs.readFile(file, 'utf8', (err, fileContent) => {
if (err) cb(err);

try {
this._writeFile({fileContent: this._changeFileContent(fileContent), filePath: file}, cb);
} catch (e) {
cb(e);
}
});
}

_changeFileContent(fileContent) {
const $ = cheerio.load(fileContent);
const swSource = `\<script src='${this.swFileName}'\>\<\/script\>\n`;
const registrationScript = `\<script\>if ('serviceWorker' in navigator) navigator.serviceWorker.register('${this.swFileName}')\<\/script\>\n`;

$('html').append(swSource, registrationScript);

return $.html();
}

_writeFile(data, cb) {
fs.writeFile(data.filePath, data.fileContent, 'utf8', (err) => {
if (err) console.log(err);
cb();
});
}

onCompile(files, assets) {
if (this.autorequire) {
const assetsList = this._getAssetsList(assets);
this._includeSWIntoAsset(assetsList);
}

return swPrecache.write(this.swFilePath, this.options);
}
}
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@
"offline first"
],
"scripts": {
"test": "node_modules/.bin/eslint index.js && node_modules/.bin/mocha"
"test": "eslint index.js && mocha"
},
"dependencies": {
"async": "^2.0.1",
"cheerio": "^0.20.0",
"sw-precache": "^4.0.0"
},
"devDependencies": {
Expand Down
51 changes: 48 additions & 3 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,23 @@ describe('Plugin', () => {

describe('Config', () => {

it('should create default service worker file', () => {
beforeEach(() => {
plugin._setConfig(config);
});

it('should set default service worker file', () => {
expect(plugin.swFileName).to.be.equal('sw.js');
expect(plugin.swFilePath).to.be.equal('public/sw.js');
});

it('should set cache all files in public by default', () => {
plugin._setConfig(config);
expect(plugin.options.staticFileGlobs[0]).to.be.equal('public/**/*.*');
});

it('should create service worker file with special name', () => {
it('should set service worker file with special name', () => {
config.plugins.swPrecache.swFileName = 'test.js';
plugin._setConfig(config);
expect(plugin.swFileName).to.be.equal('test.js');
expect(plugin.swFilePath).to.be.equal('public/test.js');
});

Expand All @@ -55,5 +59,46 @@ describe('Plugin', () => {
plugin._setConfig(config);
expect(plugin.options.staticFileGlobs).to.be.equal(staticFileGlobs);
});

describe('Autorequire', () => {
beforeEach(() => {
this.assetsList = [
{
originalPath: '',
destinationPath: 'bar.html'
},
{
originalPath: '',
destinationPath: 'baz.html'
}
];
});

it('should set false by default', () => {
expect(plugin.autorequire).to.be.false;
});

it('should set true by default', () => {
config.plugins.swPrecache.autorequire = true;
plugin._setConfig(config);
expect(plugin.autorequire).to.be.true;
});

it('should get default assets list', () => {
const expectedFilesList = ['bar.html', 'baz.html'];
config.plugins.swPrecache.autorequire = true;
plugin._setConfig(config);
const assets = plugin._getAssetsList(this.assetsList);
expect(assets).to.deep.equal(expectedFilesList);
});

it('should get configurated assets list', () => {
const filesList = ['foo.html', 'bar.html'];
config.plugins.swPrecache.autorequire = filesList;
plugin._setConfig(config);
const assets = plugin._getAssetsList(this.assetsList);
expect(assets).to.deep.equal(filesList);
});
});
});
});

0 comments on commit 105737a

Please sign in to comment.