From 8f927889a3a98d06472b662135954457385cc926 Mon Sep 17 00:00:00 2001 From: Alexander Akait <4567934+alexander-akait@users.noreply.github.com> Date: Sat, 10 Jun 2023 22:27:54 +0300 Subject: [PATCH] fix: don't add extra meta tag if it exists (#1802) --- index.js | 12 ++++++++++-- spec/basic.spec.js | 15 +++++++++++++++ spec/fixtures/src/index.ejs | 1 + 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 58799fc2..4452f636 100644 --- a/index.js +++ b/index.js @@ -76,7 +76,8 @@ class HtmlWebpackPlugin { // Default metaOptions if no template is provided if (!userOptions.template && options.templateContent === false && options.meta) { const defaultMeta = { - // From https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag + // TODO remove in the next major release + // From https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag viewport: 'width=device-width, initial-scale=1' }; options.meta = Object.assign({}, options.meta, defaultMeta, userOptions.meta); @@ -966,8 +967,15 @@ function hookIntoCompiler (compiler, options, plugin) { const htmlRegExp = /(]*>)/i; const headRegExp = /(<\/head\s*>)/i; const bodyRegExp = /(<\/body\s*>)/i; + const metaViewportRegExp = /]+name=["']viewport["'][^>]*>/i; const body = assetTags.bodyTags.map((assetTagObject) => htmlTagObjectToString(assetTagObject, options.xhtml)); - const head = assetTags.headTags.map((assetTagObject) => htmlTagObjectToString(assetTagObject, options.xhtml)); + const head = assetTags.headTags.filter((item) => { + if (item.tagName === 'meta' && item.attributes && item.attributes.name === 'viewport' && metaViewportRegExp.test(html)) { + return false; + } + + return true; + }).map((assetTagObject) => htmlTagObjectToString(assetTagObject, options.xhtml)); if (body.length) { if (bodyRegExp.test(html)) { diff --git a/spec/basic.spec.js b/spec/basic.spec.js index 5773769f..8c725fd9 100644 --- a/spec/basic.spec.js +++ b/spec/basic.spec.js @@ -1958,6 +1958,21 @@ describe('HtmlWebpackPlugin', () => { }, [//], null, done); }); + it('avoid duplicate meta tags for default template', done => { + testHtmlPlugin({ + mode: 'production', + entry: path.join(__dirname, 'fixtures/index.js'), + context: path.join(__dirname, 'fixtures'), + output: { + path: OUTPUT_DIR, + filename: 'index_bundle.js' + }, + plugins: [ + new HtmlWebpackPlugin() + ] + }, [/src\/index\.ejs<\/title><script defer="defer" src="index_bundle.js"><\/script><\/head>/], null, done); + }); + it('adds a meta tag with short notation', done => { testHtmlPlugin({ mode: 'production', diff --git a/spec/fixtures/src/index.ejs b/spec/fixtures/src/index.ejs index 3887cb1b..599e7bcd 100644 --- a/spec/fixtures/src/index.ejs +++ b/spec/fixtures/src/index.ejs @@ -2,6 +2,7 @@ <html> <head> <meta charset="utf-8"/> + <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no,viewport-fit=cover"> <title>src/index.ejs