Last active
May 4, 2024 04:24
-
-
Save ValentinFunk/35630ec21df8dca27de3bb915f2d67e4 to your computer and use it in GitHub Desktop.
Webpack - Generate Netlify HTTP2 Server Push _headers File when using the HtmlWebpackPlugin
This file contains hidden or 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 hidden or 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