diff --git a/index.js b/index.js index 45f286ad..44b76178 100644 --- a/index.js +++ b/index.js @@ -62,7 +62,8 @@ class HtmlWebpackPlugin { meta: {}, base: false, title: 'Webpack App', - xhtml: false + xhtml: false, + rootElement: false }; /** @type {ProcessedHtmlWebpackOptions} */ @@ -82,6 +83,11 @@ class HtmlWebpackPlugin { options.meta = Object.assign({}, options.meta, defaultMeta, userOptions.meta); } + // Only adds the root element if it was set + if (options.rootElement) { + options.rootElement = userOptions.rootElement; + } + // entryName to fileName conversion function const userOptionFilename = userOptions.filename || defaultOptions.filename; const filenameFunction = typeof userOptionFilename === 'function' @@ -298,6 +304,18 @@ function hookIntoCompiler (compiler, options, plugin) { (options.inject !== 'body' && options.scriptLoading !== 'blocking') ? 'head' : 'body'; // Group assets to `head` and `body` tag arrays const assetGroups = generateAssetGroups(assetTags, scriptTarget); + + if (options.rootElement) { + assetGroups.bodyTags.push({ + tagName: options.rootElement.tag || 'div', + voidTag: false, + attributes: { + id: options.rootElement.id || 'root' + }, + meta: {} + }); + } + // Allow third-party-plugin authors to reorder and change the assetTags once they are grouped return getHtmlWebpackPluginHooks(compilation).alterAssetTagGroups.promise({ headTags: assetGroups.headTags, diff --git a/spec/basic.spec.js b/spec/basic.spec.js index 794e14c6..373a4a43 100644 --- a/spec/basic.spec.js +++ b/spec/basic.spec.js @@ -2799,4 +2799,56 @@ describe('HtmlWebpackPlugin', () => { done(); }); }); + it('allows you to inject a custom root element', done => { + testHtmlPlugin({ + mode: 'none', + entry: { + app: path.join(__dirname, 'fixtures/index.js') + }, + output: { + path: OUTPUT_DIR, + filename: '[name]_bundle.js' + }, + plugins: [new HtmlWebpackPlugin({ + rootElement: { + tag: 'main', + id: 'app' + } + })] + }, [''], null, done); + }); + it('provides a default tag', done => { + testHtmlPlugin({ + mode: 'none', + entry: { + app: path.join(__dirname, 'fixtures/index.js') + }, + output: { + path: OUTPUT_DIR, + filename: '[name]_bundle.js' + }, + plugins: [new HtmlWebpackPlugin({ + rootElement: { + id: 'app' + } + })] + }, ['
'], null, done); + }); + it('provides a default id', done => { + testHtmlPlugin({ + mode: 'none', + entry: { + app: path.join(__dirname, 'fixtures/index.js') + }, + output: { + path: OUTPUT_DIR, + filename: '[name]_bundle.js' + }, + plugins: [new HtmlWebpackPlugin({ + rootElement: { + tag: 'div' + } + })] + }, [''], null, done); + }); });