Skip to content

Commit

Permalink
adding swSrc as webpack asset capability (#1763)
Browse files Browse the repository at this point in the history
* adding swSrc as webpack asset capability

* Update inject-manifest.js

* Update inject-manifest.js

* adding test

* removing unwanted code

* lint fixes
  • Loading branch information
prateekbh authored and jeffposnick committed Jan 18, 2019
1 parent 208850c commit c8b6566
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
11 changes: 10 additions & 1 deletion packages/workbox-webpack-plugin/src/inject-manifest.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,16 @@ class InjectManifest {
importScriptsArray.push(...workboxSWImports);
}

const originalSWString = await readFileWrapper(readFile, this.config.swSrc);
let originalSWString;
/**
* Check if the mentioned file name is in the webpack assets itself
* or fallback to filesystem.
*/
if (compilation.assets[this.config.swSrc]) {
originalSWString = compilation.assets[this.config.swSrc].source();
} else {
originalSWString = await readFileWrapper(readFile, this.config.swSrc);
}

// compilation.fileDependencies needs absolute paths.
const absoluteSwSrc = path.resolve(this.config.swSrc);
Expand Down
48 changes: 48 additions & 0 deletions test/workbox-webpack-plugin/node/inject-manifest.js
Original file line number Diff line number Diff line change
Expand Up @@ -1801,5 +1801,53 @@ describe(`[workbox-webpack-plugin] InjectManifest (End to End)`, function() {
}
});
});
it(`should allow swSrc to be a webpack generated asset`, function(done) {
const FILE_MANIFEST_NAME = 'precache-manifest.547bb595d8b69f77af45d81ddbd95fa1.js';
const outputDir = tempy.directory();
const publicPath = '/testing/';
const config = {
mode: 'production',
entry: {
sw: path.join(SRC_DIR, WEBPACK_ENTRY_FILENAME),
},
output: {
publicPath,
filename: '[name].js',
path: outputDir,
},
plugins: [
new InjectManifest({
swSrc: 'sw.js',
swDest: 'service-worker.js',
}),
],
optimization: {
minimize: false,
},
};

const compiler = webpack(config);
compiler.run(async (webpackError, stats) => {
if (webpackError) {
return done(webpackError);
}

try {
const statsJson = stats.toJson('verbose');
expect(statsJson.warnings).to.have.lengthOf(0);

// Check if service-worker.js is being written fine
const swSrcContents = await fse.readFile(path.join(outputDir, 'sw.js'), 'utf-8');
const swDestContents = await fse.readFile(path.join(outputDir, 'service-worker.js'), 'utf-8');
const expectedString = `importScripts("${publicPath}${FILE_MANIFEST_NAME}", ` +
`"${WORKBOX_SW_FILE_NAME}");\n\n` +
swSrcContents + '\n';
expect(expectedString).to.be.equal(swDestContents);
done();
} catch (error) {
done(error);
}
});
});
});
});

0 comments on commit c8b6566

Please sign in to comment.