Forked from ValentinFunk/NetlifyServerPushPlugin.js
Last active
January 17, 2018 08:57
-
-
Save tilsammans/8b47cf2d1be994554658f4e412ec9ea4 to your computer and use it in GitHub Desktop.
Webpack - Generate Netlify HTTP2 Server Push _headers File when using the HtmlWebpackPlugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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