Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Add javascript to be added to the webpack-built JS file directly in your HTML (for declaring dependencies, etc.)
// template.html
<script type="text/javascript-webpack-header">
console.log('loaded template');
<h1>This is the template</h1>
// nested.js
console.log('loaded nested.js');
// webpack.config.js module rules
test: /\.html$/,
use: [
results in the <script> tag being removed from the template and included as JS directly in the bundle (resulting in `nested.js` being `require`d and loaded.
// template.html built JS file
console.log('loaded template');
module.exports = '<h1>This is the template</h1>';
var path = require('path');
var headerRegex = /^\s*<script type="text\/javascript-webpack-header">\n?([\s\S]*?)<\/script>\s*/;
module.exports = function(source) {
var previousExports = this.exec(source, this.resource);
var markup = (previousExports && previousExports.default) ? previousExports.default : previousExports;
if (typeof markup !== 'string') {
throw new Error('Module ' + path.relative(process.cwd(), this.resource) + ' does not export a string as default.');
var header = '';
var replacedMarkup = markup.replace(headerRegex, function(match, captureGroup1) {
header = captureGroup1;
return '';
var returnValue = header + 'module.exports = ' + JSON.stringify(replacedMarkup);
return returnValue;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.