Forked from ValentinFunk/NetlifyServerPushPlugin.js
Created
September 30, 2018 23:13
-
-
Save pk-nb/23a8df97b26a953e074db06a8ec4d26f 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=stylesheet`); | |
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
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