Skip to content

Instantly share code, notes, and snippets.

@tilsammans
Forked from ValentinFunk/NetlifyServerPushPlugin.js
Last active January 17, 2018 08:57
Show Gist options
  • Save tilsammans/8b47cf2d1be994554658f4e412ec9ea4 to your computer and use it in GitHub Desktop.
Save tilsammans/8b47cf2d1be994554658f4e412ec9ea4 to your computer and use it in GitHub Desktop.
Webpack - Generate Netlify HTTP2 Server Push _headers File when using the HtmlWebpackPlugin
/**
* Generate a Netlify HTTP2 Server Push configuration.
*
* Options:
* - headersFile {string} path to the _headers file that should be generated (relative to your output dir)
*/
function NetlifyServerPushPlugin(options) {
this.options = options;
}
NetlifyServerPushPlugin.prototype.generateAssetHeaders = function (assets) {
// Turn script files into script tags
const scriptHeaders = assets.js.map(path => ` Link: <${path}>; rel=preload; as=script`);
const styleHeaders = assets.css.map(path => ` Link: <${path}>; rel=preload; as=style`);
return `/
${scriptHeaders.concat(styleHeaders).join('\n')}
`;
};
NetlifyServerPushPlugin.prototype.apply = function (compiler) {
compiler.plugin('compilation', (compilation) => {
compilation.plugin('html-webpack-plugin-before-html-generation', (htmlPluginData, callback) => {
const assets = htmlPluginData.assets;
const source = this.generateAssetHeaders(assets);
compilation.assets[`${this.options.headersFile}`] = {
source: () => source,
size: () => source.length
};
callback(null, htmlPluginData);
});
});
};
module.exports = NetlifyServerPushPlugin;
const NetlifyServerPushPlugin = require('./NetlifyServerPushPlugin');
module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html',
}),
new NetlifyServerPushPlugin({
headersFile: '_headers'
})
]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment