diff --git a/packages/webpack-plugin/lib/style-compiler/strip-conditional.js b/packages/webpack-plugin/lib/style-compiler/strip-conditional.js index 499f7ab6c6..243bf31381 100644 --- a/packages/webpack-plugin/lib/style-compiler/strip-conditional.js +++ b/packages/webpack-plugin/lib/style-compiler/strip-conditional.js @@ -147,16 +147,90 @@ function traverseAndEvaluate(ast, defs) { } /** - * + *处理普通字符串的内部方法 * @param {string} content * @param {Record} defs * @returns */ -function stripCondition(content, defs) { +function doStripCondition(content, defs) { const ast = parse(content) return traverseAndEvaluate(ast, defs) } +/** + * 检测内容中是否包含条件编译指令 + * @param {string} content + * @returns {boolean} + */ +function hasConditionalDirective(content) { + const regex = /(?:\/\*\s*@mpx-(if|elif|else|endif)(?:\s*\([\s\S]*?\))?\s*\*\/)|(?:\/\/\s*@mpx-(if|elif|else|endif)(?:\s*\(.*?\))?\s*)|(?:)/ + return regex.test(content) +} + +/** + * 处理 .mpx 文件内容: + * 1. 仅对 块(支持多个 style 块) + const styleRegex = /(]*>)([\s\S]*?)(<\/style>)/gi + let lastIndex = 0 + let result = '' + let match + + while ((match = styleRegex.exec(content)) !== null) { + // match.index 到 match[1] 结束前的内容为非 style 区域 + const beforeStyle = content.substring(lastIndex, match.index) + // 检测非 style 区域是否包含条件指令 + if (hasConditionalDirective(beforeStyle)) { + logStripError(path, new Error('@mpx conditional directives are only allowed inside ` + const result = stripCondition(input, defs, '/test/app.mpx') + expect(result).toContain('Hello') + expect(result).toContain('.wx-only { color: red; }') + expect(result).not.toContain('.ali-only { color: blue; }') + }) + + it('should handle multiple +` + const result = stripCondition(input, defs, '/test/app.mpx') + expect(result).toContain('.block1 { color: red; }') + expect(result).toContain('.block2 { background: #000; }') + expect(result).not.toContain('.block3 { background: #fff; }') + }) + + it('should return original content and log error when conditional directive appears in