From d6c4e697245f0a727334e3e86329dafa05c01a25 Mon Sep 17 00:00:00 2001 From: wkj <278599135@qq.com> Date: Fri, 29 Apr 2022 12:12:44 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=BF=E6=8D=A2xmldom=E7=94=9F=E6=88=90?= =?UTF-8?q?=E7=9A=84=E6=97=A0=E5=80=BC=E5=B1=9E=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/loaders/wxml-loader.js | 69 +++++++++++++++++++++++++++++++++-- 1 file changed, 65 insertions(+), 4 deletions(-) diff --git a/config/loaders/wxml-loader.js b/config/loaders/wxml-loader.js index 3ab7b07..0754781 100644 --- a/config/loaders/wxml-loader.js +++ b/config/loaders/wxml-loader.js @@ -2,13 +2,49 @@ * * @param {*} content 文件信息 */ -const { DOMParser, XMLSerializer } = require('@xmldom/xmldom') +const { DOMParser, XMLSerializer } = require('@xmldom/xmldom'); +const BOOLEAN_ATTRS = [ + 'wx:else', + 'show-info', + 'active', + 'controls', + 'danmu-btn', + 'enable-danmu', + 'autoplay', + 'disabled', + 'show-value', + 'checked', + 'scroll-x', + 'scroll-y', + 'auto-focus', + 'focus', + 'auto-height', + 'password', + 'indicator-dots', + 'report-submit', + 'hidden', + 'plain', + 'loading', + 'redirect', + 'loop', + 'controls', +]; + +// 替换xmldom生成的无值属性 +function replaceBooleanAttr(code) { + let reg; + BOOLEAN_ATTRS.forEach((v) => { + reg = new RegExp(`${v}=['"]${v}['"]`, 'ig'); + code = code.replace(reg, v); + }); + return code; +} function traverse(doc, callback) { callback(doc); if (doc.childNodes) { const { length } = doc.childNodes; - for (let i = 0; i < length; i ++) { + for (let i = 0; i < length; i++) { traverse(doc.childNodes.item(i), callback); } } @@ -17,12 +53,36 @@ function traverse(doc, callback) { module.exports = function (content) { const options = this.getOptions() || {}; //获取配置参数 // const callback = this.async(); + const { options: webpackLegacyOptions, _module = {}, resourcePath } = this; + const { context, target } = webpackLegacyOptions || this; + // console.log(context, target); + + if (/miniprogram_npm/.test(context)) { + return content; + } + if ( + /node_modules/.test(context) && + !/oak-general-business\/wechatMp/.test(context) + ) { + return content; + } // console.log(content, options); /** * domparser会自动给没有value的attribute赋上值,目前改不动 */ - const doc = new DOMParser().parseFromString(content, 'text/xml'); + const doc = new DOMParser({ + errorHandler: { + warning(x) { + if ( + x.indexOf('missed value!!') === -1 && + x.indexOf('missed quot(")!') === -1 + ) { + console.log(x); + } + }, + }, + }).parseFromString(content, 'text/xml'); traverse(doc, (node) => { if (node.nodeType === node.ELEMENT_NODE) { // 处理oak:value声明的属性 @@ -42,5 +102,6 @@ module.exports = function (content) { }); const serialized = new XMLSerializer().serializeToString(doc); - return serialized; + const code = replaceBooleanAttr(serialized); + return code; };