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; };