diff --git a/examples/javascript/template.js b/examples/javascript/template.js index 0dbe82a..d6c1c33 100644 --- a/examples/javascript/template.js +++ b/examples/javascript/template.js @@ -2,4 +2,4 @@ var partial = require('./partial.html'); // Export a function / promise / or a string: -module.exports = '' + new Date() + partial + ''; +module.exports = new Date() + partial; diff --git a/index.js b/index.js index 49f45b1..5859453 100644 --- a/index.js +++ b/index.js @@ -442,8 +442,11 @@ HtmlWebpackPlugin.prototype.injectAssetsIntoHtml = function(html, assets) { return ''; }); // Injections + var htmlRegExp = /(]*>)/i; var head = []; + var headRegExp = /(<\/head>)/i; var body = []; + var bodyRegExp = /(<\/body>)/i; // If there is a favicon present, add it to the head if (assets.favicon) { @@ -457,14 +460,37 @@ HtmlWebpackPlugin.prototype.injectAssetsIntoHtml = function(html, assets) { } else { body = body.concat(scripts); } - // Append assets to head element - html = html.replace(/(<\/head>)/i, function (match) { - return head.join('') + match; - }); - // Append assets to body element - html = html.replace(/(<\/body>)/i, function (match) { - return body.join('') + match; + + if (body.length) { + if(bodyRegExp.test(html)) { + // Append assets to body element + html = html.replace(bodyRegExp, function (match) { + return body.join('') + match; + }); + } else { + // Append scripts to the end of the file if no element exists: + html += body.join(''); + } + } + + if (head.length) { + // Create a head tag if none exists + if (!headRegExp.test(html)) { + if (!htmlRegExp.test(html)) { + html = '' + html; + } else { + html = html.replace(htmlRegExp, function(match) { + return match + ''; + }); + } + } + + // Append assets to head element + html = html.replace(headRegExp, function (match) { + return head.join('') + match; }); + } + // Inject manifest into the opening html tag if (assets.manifest) { html = html.replace(/(]*)(>)/i, function (match, start, end) { diff --git a/spec/HtmlWebpackPluginSpec.js b/spec/HtmlWebpackPluginSpec.js index 0897466..95e728f 100644 --- a/spec/HtmlWebpackPluginSpec.js +++ b/spec/HtmlWebpackPluginSpec.js @@ -1,6 +1,6 @@ 'use strict'; -// Workaround for css-loader issue +// Workaround for css-loader issue // https://github.com/webpack/css-loader/issues/144 if (!global.Promise) { require('es6-promise').polyfill(); @@ -311,7 +311,7 @@ describe('HtmlWebpackPlugin', function() { filename: 'index_bundle_[hash].js' }, plugins: [new HtmlWebpackPlugin()] - }, [/