From 47f0db8bf30fa62e58d279608504378c54f5f8c4 Mon Sep 17 00:00:00 2001 From: mackwang Date: Sat, 22 Jun 2024 18:05:14 +0800 Subject: [PATCH 01/10] =?UTF-8?q?production=E6=A8=A1=E5=BC=8F=E5=8E=8B?= =?UTF-8?q?=E7=BC=A9=E7=BB=84=E4=BB=B6=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../webpack-plugin/lib/json-compiler/index.js | 27 ++++++ .../lib/template-compiler/index.js | 28 ++++++ .../lib/utils/get-compress-key.js | 90 +++++++++++++++++++ 3 files changed, 145 insertions(+) create mode 100644 packages/webpack-plugin/lib/utils/get-compress-key.js diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index 243e6bf47a..87e501dc1a 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -18,6 +18,7 @@ const resolveTabBarPath = require('../utils/resolve-tab-bar-path') const normalize = require('../utils/normalize') const mpxViewPath = normalize.lib('runtime/components/ali/mpx-view.mpx') const mpxTextPath = normalize.lib('runtime/components/ali/mpx-text.mpx') +const { generatorVariableNameBySource } = require('../utils/get-compress-key') module.exports = function (content) { const nativeCallback = this.async() @@ -173,6 +174,32 @@ module.exports = function (content) { } } + if (this.mode === 'production' && mode !== 'web') { + // placeholder 替换 + if (json.componentPlaceholder) { + const newComponentPlaceholder = {} + for (const [name, value] of Object.entries(json.componentPlaceholder)) { + const newName = generatorVariableNameBySource(name, this.resourcePath + 'componentName') + newComponentPlaceholder[newName] = json.componentPlaceholder[name] + delete json.componentPlaceholder[name] + if (value in json.usingComponents) { + newComponentPlaceholder[newName] = generatorVariableNameBySource(value, this.resourcePath + 'componentName') + } + } + Object.assign(json.componentPlaceholder, newComponentPlaceholder) + } + // usingComponents 替换 + if (json.usingComponents) { + const newUsingComponents = {} + for (const name of Object.keys(json.usingComponents)) { + const newName = generatorVariableNameBySource(name, this.resourcePath + 'componentName') + newUsingComponents[newName] = json.usingComponents[name] + delete json.usingComponents[name] + } + Object.assign(json.usingComponents, newUsingComponents) + } + } + // 快应用补全json配置,必填项 if (mode === 'qa' && isApp) { const defaultConf = { diff --git a/packages/webpack-plugin/lib/template-compiler/index.js b/packages/webpack-plugin/lib/template-compiler/index.js index 9e2019a15a..ae49e01eb1 100644 --- a/packages/webpack-plugin/lib/template-compiler/index.js +++ b/packages/webpack-plugin/lib/template-compiler/index.js @@ -3,6 +3,7 @@ const bindThis = require('./bind-this') const parseRequest = require('../utils/parse-request') const { matchCondition } = require('../utils/match-condition') const loaderUtils = require('loader-utils') +const { generatorVariableNameBySource } = require('../utils/get-compress-key') module.exports = function (raw) { this.cacheable() @@ -74,6 +75,33 @@ module.exports = function (raw) { hasVirtualHost: matchCondition(resourcePath, mpx.autoVirtualHostRules) }) + // 组件名压缩 + if (this.mode === 'production' && mode !== 'web') { + function walkNode(root, callback) { + if (!root) return + callback(root) + if (Array.isArray(root.children) && root.children.length) { + for (const node of root.children) { + if (!node) continue + walkNode(node, callback) + } + } + } + // 记录所有原生组件(判断条件:usingComponents中不存在的组件) + const nativeTags = new Set() + walkNode(ast, (node) => { + if (node.tag && usingComponents.indexOf(node.tag) === -1) { + nativeTags.add(node.tag) + } + }) + walkNode(ast, (node) => { + // 只有自定义组件才替换(判断条件:在usingComponents中的组件),并且新组件名不允许出现原生组件名 + if (node.tag && usingComponents.indexOf(node.tag) !== -1) { + node.tag = generatorVariableNameBySource(node.tag, resourcePath + 'componentName', [...nativeTags]) + } + }) + } + if (meta.wxsContentMap) { for (const module in meta.wxsContentMap) { wxsContentMap[`${resourcePath}~${module}`] = meta.wxsContentMap[module] diff --git a/packages/webpack-plugin/lib/utils/get-compress-key.js b/packages/webpack-plugin/lib/utils/get-compress-key.js new file mode 100644 index 0000000000..911fdc08a4 --- /dev/null +++ b/packages/webpack-plugin/lib/utils/get-compress-key.js @@ -0,0 +1,90 @@ +class CompressName { + constructor(chars, allowStartChars) { + this._arr = [] + // this._occupiedNames = new Set() + this._compressMap = new Map() + // 允许使用的字符, 需要去重 + this.chars = typeof chars === 'string' ? [...new Set(chars.split(''))].join('') : 'abcdefghijklmnopqrstuvwxyz' + // 首个字符允许的字符(生产变量名时用于指定禁止数字开头) + this.allowStartChars = [...new Set(allowStartChars.split(''))].join('') || this.chars + + // 检查一下allowStartChars必须都在char中,以防运行阶段出现死循环 + for (const char of this.allowStartChars) { + if (this.chars.indexOf(char) === -1) { + throw new Error(`CompressName allowStartChars 包含 chars 中不存在的字符: "${char}"`) + } + } + } + + _findStartCharIndex(startIndex) { + for (let i = startIndex; i < this.chars.length; i++) { + if (this.allowStartChars.indexOf(this.chars[i]) !== -1) { + return i + } + } + return -1 + } + + _generatorName() { + if (this._arr.length === 0) { + this._arr[0] = this._findStartCharIndex(0) + } else { + if (this._arr.length === 1) { + this._arr[0] = this._findStartCharIndex(this._arr[0] + 1) + if (this._arr[0] === -1) this._arr[0] = this.chars.length + } else { + this._arr[this._arr.length - 1]++ + } + for (let i = this._arr.length - 1; i >= 0; i--) { + if (this._arr[i] === this.chars.length) { + this._arr[i] = 0 + if (i == 0) { + this._arr.unshift(this._findStartCharIndex(0)) + } else if (i == 1) { + this._arr[i - 1] = this._findStartCharIndex(this._arr[i - 1] + 1) + if (this._arr[i - 1] === -1) this._arr[i - 1] = this.chars.length + } else { + this._arr[i - 1]++ + } + } + } + } + return this._arr.map(num => this.chars[num]).join('') + } + + // 指定不允许使用的key + // occupiedKey: string[] | string + _occupiedGeneratorName(occupiedKey) { + let key = this._generatorName() + + if (!occupiedKey) return key + if (typeof occupiedKey === 'string') occupiedKey = [occupiedKey] + + while (occupiedKey.indexOf(key) !== -1) { + key = this._generatorName() + } + return key + } + + compress(source, occupiedKey) { + if (!this._compressMap.has(source)) { + this._compressMap.set(source, this._occupiedGeneratorName(occupiedKey)) + // this._occupiedNames.add(this._compressMap.get(source)) + } + return this._compressMap.get(source) + } +} + + +const namespaces = {} +function generatorVariableNameBySource(source, namespace, occupiedKey) { + if (!namespaces[namespace]) { + // 限制只能字母开头 + namespaces[namespace] = new CompressName('abcdefghijklmnopqrstuvwxyz_-0123456789', 'abcdefghijklmnopqrstuvwxyz') + } + return namespaces[namespace].compress(source) +} + +module.exports = { + generatorVariableNameBySource +} From d5cc59e154f8d6823a7f15d3319c44e4000847e9 Mon Sep 17 00:00:00 2001 From: xuegan Date: Mon, 24 Jun 2024 16:26:42 +0800 Subject: [PATCH 02/10] =?UTF-8?q?feat:=20=E7=AE=80=E5=8C=96webpack-plugin?= =?UTF-8?q?=E6=B3=A8=E5=85=A5=E5=85=A8=E5=B1=80key?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/core/src/core/transferOptions.js | 9 ++++++--- packages/core/src/platform/createApp.js | 5 +++-- packages/core/src/platform/patch/index.js | 16 ++++++++++------ packages/webpack-plugin/lib/loader.js | 16 ++++++++++------ packages/webpack-plugin/lib/native-loader.js | 16 ++++++++++------ .../lib/template-compiler/index.js | 12 ++++++------ packages/webpack-plugin/lib/web/script-helper.js | 9 ++++++--- 7 files changed, 51 insertions(+), 32 deletions(-) diff --git a/packages/core/src/core/transferOptions.js b/packages/core/src/core/transferOptions.js index f4ebbae1d6..26b2f76ba9 100644 --- a/packages/core/src/core/transferOptions.js +++ b/packages/core/src/core/transferOptions.js @@ -5,8 +5,10 @@ import { warn, findItem } from '@mpxjs/utils' export default function transferOptions (options, type, needConvert = true) { let currentInject - if (global.currentInject && global.currentInject.moduleId === global.currentModuleId) { - currentInject = global.currentInject + // currentModuleId -> _mid + // currentInject -> _cj + if (global._cj && global._cj.moduleId === global._mid) { + currentInject = global._cj } // 文件编译路径 options.mpxFileResource = global.currentResource @@ -28,7 +30,8 @@ export default function transferOptions (options, type, needConvert = true) { options.mixins.push(currentInject.pageEvents) } // 转换mode - options.mpxConvertMode = options.mpxConvertMode || getConvertMode(global.currentSrcMode) + // currentSrcMode -> _sm + options.mpxConvertMode = options.mpxConvertMode || getConvertMode(global._sm) const rawOptions = mergeOptions(options, type, needConvert) if (currentInject && currentInject.propKeys) { diff --git a/packages/core/src/platform/createApp.js b/packages/core/src/platform/createApp.js index 22a635abb9..b47748ef38 100644 --- a/packages/core/src/platform/createApp.js +++ b/packages/core/src/platform/createApp.js @@ -82,7 +82,8 @@ export default function createApp (option, config = {}) { if (__mpx_mode__ === 'web') { global.__mpxOptionsMap = global.__mpxOptionsMap || {} - global.__mpxOptionsMap[global.currentModuleId] = defaultOptions + // currentModuleId -> _mid + global.__mpxOptionsMap[global._mid] = defaultOptions global.getApp = function () { if (!isBrowser) { console.error('[Mpx runtime error]: Dangerous API! global.getApp method is running in non browser environments') @@ -90,7 +91,7 @@ export default function createApp (option, config = {}) { return appData } } else { - const ctor = config.customCtor || global.currentCtor || App + const ctor = config.customCtor || global._ctor || App ctor(defaultOptions) } } diff --git a/packages/core/src/platform/patch/index.js b/packages/core/src/platform/patch/index.js index 80719e299c..ca09841873 100644 --- a/packages/core/src/platform/patch/index.js +++ b/packages/core/src/platform/patch/index.js @@ -19,13 +19,16 @@ export default function createFactory (type) { options.__pageCtor__ = true } } else { - if (global.currentCtor) { - ctor = global.currentCtor - if (global.currentCtorType === 'page') { + // currentCtor -> _ctor + if (global._ctor) { + ctor = global._ctor + // currentCtorType -> _ctorT + if (global._ctorT === 'page') { options.__pageCtor__ = true } - if (global.currentResourceType && global.currentResourceType !== type) { - error(`The ${global.currentResourceType} [${global.currentResource}] is not supported to be created by ${type} constructor.`) + // currentResourceType -> _crt + if (global._crt && global._crt !== type) { + error(`The ${global._crt} [${global.currentResource}] is not supported to be created by ${type} constructor.`) } } else { if (type === 'page') { @@ -59,7 +62,8 @@ export default function createFactory (type) { const defaultOptions = getDefaultOptions(type, { rawOptions, currentInject }) if (__mpx_mode__ === 'web') { global.__mpxOptionsMap = global.__mpxOptionsMap || {} - global.__mpxOptionsMap[global.currentModuleId] = defaultOptions + // currentModuleId -> _mid + global.__mpxOptionsMap[global._mid] = defaultOptions } else if (ctor) { return ctor(defaultOptions) } diff --git a/packages/webpack-plugin/lib/loader.js b/packages/webpack-plugin/lib/loader.js index 3ef11429e1..97d40ae3b9 100644 --- a/packages/webpack-plugin/lib/loader.js +++ b/packages/webpack-plugin/lib/loader.js @@ -249,7 +249,8 @@ module.exports = function (content) { } // 注入模块id及资源路径 - output += `global.currentModuleId = ${JSON.stringify(moduleId)}\n` + // currentModuleId -> _mid + output += `global._mid = ${JSON.stringify(moduleId)}\n` if (!isProduction) { output += `global.currentResource = ${JSON.stringify(filePath)}\n` } @@ -279,12 +280,14 @@ module.exports = function (content) { : ctorType === 'component' ? 'Component' : 'App' - - output += `global.currentCtor = ${ctor}\n` - output += `global.currentCtorType = ${JSON.stringify(ctor.replace(/^./, (match) => { + // currentCtor -> _ctor + output += `global._ctor = ${ctor}\n` + // currentCtorType -> _ctorT + output += `global._ctorT = ${JSON.stringify(ctor.replace(/^./, (match) => { return match.toLowerCase() }))}\n` - output += `global.currentResourceType = ${JSON.stringify(ctorType)}\n` + // currentResourceType -> _crt + output += `global._crt = ${JSON.stringify(ctorType)}\n` // template output += '/* template */\n' @@ -345,7 +348,8 @@ module.exports = function (content) { const script = parts.script || {} if (script) { scriptSrcMode = script.mode || scriptSrcMode - if (scriptSrcMode) output += `global.currentSrcMode = ${JSON.stringify(scriptSrcMode)}\n` + // currentSrcMode -> _sm + if (scriptSrcMode) output += `global._sm = ${JSON.stringify(scriptSrcMode)}\n` // 传递ctorType以补全js内容 const extraOptions = { ...script.src diff --git a/packages/webpack-plugin/lib/native-loader.js b/packages/webpack-plugin/lib/native-loader.js index 052329e7ff..d2c63ee3e6 100644 --- a/packages/webpack-plugin/lib/native-loader.js +++ b/packages/webpack-plugin/lib/native-loader.js @@ -241,19 +241,23 @@ module.exports = function (content) { } // 注入模块id及资源路径 - let output = `global.currentModuleId = ${JSON.stringify(moduleId)}\n` + // currentModuleId -> _mid + let output = `global._mid = ${JSON.stringify(moduleId)}\n` if (!isProduction) { output += `global.currentResource = ${JSON.stringify(filePath)}\n` } - - output += `global.currentCtor = ${ctor}\n` - output += `global.currentCtorType = ${JSON.stringify(ctor.replace(/^./, (match) => { + // currentCtor -> _ctor + output += `global._ctor = ${ctor}\n` + // currentCtorType -> _ctorT + output += `global._ctorT = ${JSON.stringify(ctor.replace(/^./, (match) => { return match.toLowerCase() }))}\n` - output += `global.currentResourceType = ${JSON.stringify(ctorType)}\n` + // currentResourceType -> _crt + output += `global._crt = ${JSON.stringify(ctorType)}\n` if (srcMode) { - output += `global.currentSrcMode = ${JSON.stringify(srcMode)}\n` + // currentSrcMode -> _sm + output += `global._sm = ${JSON.stringify(srcMode)}\n` } for (const type in typeResourceMap) { diff --git a/packages/webpack-plugin/lib/template-compiler/index.js b/packages/webpack-plugin/lib/template-compiler/index.js index ae49e01eb1..26a3259773 100644 --- a/packages/webpack-plugin/lib/template-compiler/index.js +++ b/packages/webpack-plugin/lib/template-compiler/index.js @@ -120,9 +120,9 @@ module.exports = function (raw) { const src = loaderUtils.urlToRequest(meta.wxsModuleMap[module], root) resultSource += `var ${module} = require(${loaderUtils.stringifyRequest(this, src)});\n` } - + // currentInject -> _cj resultSource += ` -global.currentInject = { +global._cj = { moduleId: ${JSON.stringify(moduleId)} };\n` @@ -145,7 +145,7 @@ global.currentInject = { ignoreMap }) resultSource += ` -global.currentInject.render = function (_i, _c, _r, _sc) { +global._cj.render = function (_i, _c, _r, _sc) { ${bindResult.code} _r(${optimizeRenderLevel === 2 ? 'true' : ''}); };\n` @@ -167,20 +167,20 @@ ${e.stack}`) if (meta.computed) { resultSource += bindThis.transform(` -global.currentInject.injectComputed = { +global._cj.injectComputed = { ${meta.computed.join(',')} };`).code + '\n' } if (meta.refs) { resultSource += ` -global.currentInject.getRefsData = function () { +global._cj.getRefsData = function () { return ${JSON.stringify(meta.refs)}; };\n` } if (meta.options) { - resultSource += `global.currentInject.injectOptions = ${JSON.stringify(meta.options)};` + '\n' + resultSource += `global._cj.injectOptions = ${JSON.stringify(meta.options)};` + '\n' } this.emitFile(resourcePath, '', undefined, { diff --git a/packages/webpack-plugin/lib/web/script-helper.js b/packages/webpack-plugin/lib/web/script-helper.js index 2eb891c153..6f27a31b71 100644 --- a/packages/webpack-plugin/lib/web/script-helper.js +++ b/packages/webpack-plugin/lib/web/script-helper.js @@ -182,9 +182,12 @@ function buildGlobalParams ({ global.__mpxOptionsMap = global.__mpxOptionsMap || {} global.__mpxTransRpxFn = ${webConfig.transRpxFn} \n` } - content += ` global.currentModuleId = ${JSON.stringify(moduleId)}\n` - content += ` global.currentSrcMode = ${JSON.stringify(scriptSrcMode)}\n` - content += ` global.currentInject = ${JSON.stringify({ moduleId })}\n` + // currentModuleId -> _mid + content += ` global._mid = ${JSON.stringify(moduleId)}\n` + // currentSrcMode -> _sm + content += ` global._sm = ${JSON.stringify(scriptSrcMode)}\n` + // currentInject -> _cj + content += ` global._cj = ${JSON.stringify({ moduleId })}\n` if (!isProduction) { content += ` global.currentResource = ${JSON.stringify(loaderContext.resourcePath)}\n` } From 74f28b71d48a5e045f452f90d3cba5634bbcfda8 Mon Sep 17 00:00:00 2001 From: xuegan Date: Mon, 24 Jun 2024 17:04:41 +0800 Subject: [PATCH 03/10] =?UTF-8?q?feat:=20componentPath=20=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E8=B7=AF=E5=BE=84=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/webpack-plugin/lib/index.js | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/webpack-plugin/lib/index.js b/packages/webpack-plugin/lib/index.js index 8747a9de17..f0a17bd3ef 100644 --- a/packages/webpack-plugin/lib/index.js +++ b/packages/webpack-plugin/lib/index.js @@ -63,6 +63,7 @@ const stringifyLoadersAndResource = require('./utils/stringify-loaders-resource' const emitFile = require('./utils/emit-file') const { MPX_PROCESSED_FLAG, MPX_DISABLE_EXTRACTOR_CACHE } = require('./utils/const') const isEmptyObject = require('./utils/is-empty-object') +const generatorVariableNameBySource = require('./utils/get-compress-key') require('./utils/check-core-version-match') const isProductionLikeMode = options => { @@ -701,7 +702,15 @@ class MpxWebpackPlugin { const customOutputPath = this.options.customOutputPath if (conflictPath) return conflictPath.replace(/(\.[^\\/]+)?$/, match => hash + match) if (typeof customOutputPath === 'function') return customOutputPath(type, name, hash, ext).replace(/^\//, '') - if (type === 'component' || type === 'page') return path.join(type + 's', name + hash, 'index' + ext) + if (type === 'component') { + if (this.options.optimizeSize && isProductionLikeMode(compiler.options)) { + const pathHash = generatorVariableNameBySource(resourcePath, 'componentPath') + return path.join('c', pathHash, 'i' + ext) + } else { + return path.join('c', name + hash, 'i' + ext) + } + } + if (type === 'page') return path.join(type + 's', name + hash, 'index' + ext) return path.join(type, name + hash + ext) }, extractedFilesCache: new Map(), From 9c41b374b86306935f484a5dd8175ead5d1581e7 Mon Sep 17 00:00:00 2001 From: mackwang Date: Mon, 24 Jun 2024 17:44:04 +0800 Subject: [PATCH 04/10] fix: fix eslint --- packages/webpack-plugin/lib/index.js | 4 +- .../webpack-plugin/lib/json-compiler/index.js | 14 ++++--- .../lib/template-compiler/index.js | 12 ++++-- .../lib/utils/get-compress-key.js | 42 ++++++++++++------- 4 files changed, 45 insertions(+), 27 deletions(-) diff --git a/packages/webpack-plugin/lib/index.js b/packages/webpack-plugin/lib/index.js index f0a17bd3ef..bdefdb1c1d 100644 --- a/packages/webpack-plugin/lib/index.js +++ b/packages/webpack-plugin/lib/index.js @@ -63,7 +63,7 @@ const stringifyLoadersAndResource = require('./utils/stringify-loaders-resource' const emitFile = require('./utils/emit-file') const { MPX_PROCESSED_FLAG, MPX_DISABLE_EXTRACTOR_CACHE } = require('./utils/const') const isEmptyObject = require('./utils/is-empty-object') -const generatorVariableNameBySource = require('./utils/get-compress-key') +const generateVariableNameBySource = require('./utils/get-compress-key') require('./utils/check-core-version-match') const isProductionLikeMode = options => { @@ -704,7 +704,7 @@ class MpxWebpackPlugin { if (typeof customOutputPath === 'function') return customOutputPath(type, name, hash, ext).replace(/^\//, '') if (type === 'component') { if (this.options.optimizeSize && isProductionLikeMode(compiler.options)) { - const pathHash = generatorVariableNameBySource(resourcePath, 'componentPath') + const pathHash = generateVariableNameBySource(resourcePath, 'componentPath') return path.join('c', pathHash, 'i' + ext) } else { return path.join('c', name + hash, 'i' + ext) diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index 87e501dc1a..3ec6a72c2b 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -18,7 +18,11 @@ const resolveTabBarPath = require('../utils/resolve-tab-bar-path') const normalize = require('../utils/normalize') const mpxViewPath = normalize.lib('runtime/components/ali/mpx-view.mpx') const mpxTextPath = normalize.lib('runtime/components/ali/mpx-text.mpx') -const { generatorVariableNameBySource } = require('../utils/get-compress-key') +const { generateVariableNameBySource } = require('../utils/get-compress-key') + +const isProductionLikeMode = options => { + return options.mode === 'production' || !options.mode +} module.exports = function (content) { const nativeCallback = this.async() @@ -174,16 +178,16 @@ module.exports = function (content) { } } - if (this.mode === 'production' && mode !== 'web') { + if (this.options.optimizeSize && isProductionLikeMode(compiler.options) && mode !== 'web') { // placeholder 替换 if (json.componentPlaceholder) { const newComponentPlaceholder = {} for (const [name, value] of Object.entries(json.componentPlaceholder)) { - const newName = generatorVariableNameBySource(name, this.resourcePath + 'componentName') + const newName = generateVariableNameBySource(name, this.resourcePath + 'componentName') newComponentPlaceholder[newName] = json.componentPlaceholder[name] delete json.componentPlaceholder[name] if (value in json.usingComponents) { - newComponentPlaceholder[newName] = generatorVariableNameBySource(value, this.resourcePath + 'componentName') + newComponentPlaceholder[newName] = generateVariableNameBySource(value, this.resourcePath + 'componentName') } } Object.assign(json.componentPlaceholder, newComponentPlaceholder) @@ -192,7 +196,7 @@ module.exports = function (content) { if (json.usingComponents) { const newUsingComponents = {} for (const name of Object.keys(json.usingComponents)) { - const newName = generatorVariableNameBySource(name, this.resourcePath + 'componentName') + const newName = generateVariableNameBySource(name, this.resourcePath + 'componentName') newUsingComponents[newName] = json.usingComponents[name] delete json.usingComponents[name] } diff --git a/packages/webpack-plugin/lib/template-compiler/index.js b/packages/webpack-plugin/lib/template-compiler/index.js index 26a3259773..0c340f374e 100644 --- a/packages/webpack-plugin/lib/template-compiler/index.js +++ b/packages/webpack-plugin/lib/template-compiler/index.js @@ -3,7 +3,11 @@ const bindThis = require('./bind-this') const parseRequest = require('../utils/parse-request') const { matchCondition } = require('../utils/match-condition') const loaderUtils = require('loader-utils') -const { generatorVariableNameBySource } = require('../utils/get-compress-key') +const { generateVariableNameBySource } = require('../utils/get-compress-key') + +const isProductionLikeMode = options => { + return options.mode === 'production' || !options.mode +} module.exports = function (raw) { this.cacheable() @@ -76,8 +80,8 @@ module.exports = function (raw) { }) // 组件名压缩 - if (this.mode === 'production' && mode !== 'web') { - function walkNode(root, callback) { + if (this.options.optimizeSize && isProductionLikeMode(compiler.options) && mode !== 'web') { + function walkNode (root, callback) { if (!root) return callback(root) if (Array.isArray(root.children) && root.children.length) { @@ -97,7 +101,7 @@ module.exports = function (raw) { walkNode(ast, (node) => { // 只有自定义组件才替换(判断条件:在usingComponents中的组件),并且新组件名不允许出现原生组件名 if (node.tag && usingComponents.indexOf(node.tag) !== -1) { - node.tag = generatorVariableNameBySource(node.tag, resourcePath + 'componentName', [...nativeTags]) + node.tag = generateVariableNameBySource(node.tag, resourcePath + 'componentName', [...nativeTags]) } }) } diff --git a/packages/webpack-plugin/lib/utils/get-compress-key.js b/packages/webpack-plugin/lib/utils/get-compress-key.js index 911fdc08a4..6e3953f3df 100644 --- a/packages/webpack-plugin/lib/utils/get-compress-key.js +++ b/packages/webpack-plugin/lib/utils/get-compress-key.js @@ -1,6 +1,6 @@ class CompressName { - constructor(chars, allowStartChars) { - this._arr = [] + constructor (chars, allowStartChars) { + this._arr = [0] // this._occupiedNames = new Set() this._compressMap = new Map() // 允许使用的字符, 需要去重 @@ -16,7 +16,8 @@ class CompressName { } } - _findStartCharIndex(startIndex) { + // 用于获取符合首字母规则的字符的下标 + _findStartCharIndex (startIndex) { for (let i = startIndex; i < this.chars.length; i++) { if (this.allowStartChars.indexOf(this.chars[i]) !== -1) { return i @@ -25,66 +26,75 @@ class CompressName { return -1 } - _generatorName() { + _generateName () { if (this._arr.length === 0) { + // 首次生成,获取首字母 this._arr[0] = this._findStartCharIndex(0) } else { if (this._arr.length === 1) { + // 只有一个字母,从当前位置往后获取首字母 this._arr[0] = this._findStartCharIndex(this._arr[0] + 1) + // 如果获取不到,则直接设置到最大值,后面在来做进位处理 if (this._arr[0] === -1) this._arr[0] = this.chars.length } else { + // 最后一个字母(非首字母),+1即可 this._arr[this._arr.length - 1]++ } + + // 进位处理,如果数组中某一位 = chars.length,则前一项+1,当前项为0 for (let i = this._arr.length - 1; i >= 0; i--) { if (this._arr[i] === this.chars.length) { this._arr[i] = 0 - if (i == 0) { + if (i === 0) { + // 当前为第一位,则再补充一个最小的首位: [10,0] -> [1,0,0] this._arr.unshift(this._findStartCharIndex(0)) - } else if (i == 1) { + } else if (i === 1) { + // 当前为第二位,进位会影响首位,也需要findStartCharIndex this._arr[i - 1] = this._findStartCharIndex(this._arr[i - 1] + 1) if (this._arr[i - 1] === -1) this._arr[i - 1] = this.chars.length } else { + // 其他情况,正常进位即可 this._arr[i - 1]++ } } } } + // 获取每一位对应的字符拼接 return this._arr.map(num => this.chars[num]).join('') } // 指定不允许使用的key // occupiedKey: string[] | string - _occupiedGeneratorName(occupiedKey) { - let key = this._generatorName() + _occupiedGenerateName (occupiedKey) { + let key = this._generateName() if (!occupiedKey) return key if (typeof occupiedKey === 'string') occupiedKey = [occupiedKey] while (occupiedKey.indexOf(key) !== -1) { - key = this._generatorName() + key = this._generateName() } return key } - compress(source, occupiedKey) { + compress (source, occupiedKey) { if (!this._compressMap.has(source)) { - this._compressMap.set(source, this._occupiedGeneratorName(occupiedKey)) + this._compressMap.set(source, this._occupiedGenerateName(occupiedKey)) // this._occupiedNames.add(this._compressMap.get(source)) } return this._compressMap.get(source) } } - const namespaces = {} -function generatorVariableNameBySource(source, namespace, occupiedKey) { +function generateVariableNameBySource (source, namespace, occupiedKey) { if (!namespaces[namespace]) { // 限制只能字母开头 - namespaces[namespace] = new CompressName('abcdefghijklmnopqrstuvwxyz_-0123456789', 'abcdefghijklmnopqrstuvwxyz') + namespaces[namespace] = new CompressName('abcdefghijklmnopqrstuvwxyz_0123456789', 'abcdefghijklmnopqrstuvwxyz') } - return namespaces[namespace].compress(source) + return namespaces[namespace].compress(source, occupiedKey) } module.exports = { - generatorVariableNameBySource + generateVariableNameBySource } From 1e0544841a12de19405e9877cda24aab6fba47e2 Mon Sep 17 00:00:00 2001 From: mackwang Date: Mon, 24 Jun 2024 22:08:29 +0800 Subject: [PATCH 05/10] =?UTF-8?q?style:=20=E8=B0=83=E6=95=B4=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E7=BB=93=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/webpack-plugin/lib/index.js | 7 +- .../webpack-plugin/lib/json-compiler/index.js | 67 ++++++++++--------- .../lib/template-compiler/compiler.js | 32 +++++++++ .../lib/template-compiler/index.js | 34 +--------- ...t-compress-key.js => optimize-compress.js} | 9 ++- 5 files changed, 79 insertions(+), 70 deletions(-) rename packages/webpack-plugin/lib/utils/{get-compress-key.js => optimize-compress.js} (95%) diff --git a/packages/webpack-plugin/lib/index.js b/packages/webpack-plugin/lib/index.js index bdefdb1c1d..8f9acc9494 100644 --- a/packages/webpack-plugin/lib/index.js +++ b/packages/webpack-plugin/lib/index.js @@ -63,13 +63,9 @@ const stringifyLoadersAndResource = require('./utils/stringify-loaders-resource' const emitFile = require('./utils/emit-file') const { MPX_PROCESSED_FLAG, MPX_DISABLE_EXTRACTOR_CACHE } = require('./utils/const') const isEmptyObject = require('./utils/is-empty-object') -const generateVariableNameBySource = require('./utils/get-compress-key') +const { generateVariableNameBySource, isProductionLikeMode } = require('./utils/optimize-compress') require('./utils/check-core-version-match') -const isProductionLikeMode = options => { - return options.mode === 'production' || !options.mode -} - const isStaticModule = module => { if (!module.resource) return false const { queryObj } = parseRequest(module.resource) @@ -671,6 +667,7 @@ class MpxWebpackPlugin { }, asyncSubpackageRules: this.options.asyncSubpackageRules, optimizeRenderRules: this.options.optimizeRenderRules, + optimizeSize: this.options.optimizeSize, pathHash: (resourcePath) => { if (this.options.pathHashMode === 'relative' && this.options.projectRoot) { return hash(path.relative(this.options.projectRoot, resourcePath)) diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index 3ec6a72c2b..a09db1eaba 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -18,11 +18,7 @@ const resolveTabBarPath = require('../utils/resolve-tab-bar-path') const normalize = require('../utils/normalize') const mpxViewPath = normalize.lib('runtime/components/ali/mpx-view.mpx') const mpxTextPath = normalize.lib('runtime/components/ali/mpx-text.mpx') -const { generateVariableNameBySource } = require('../utils/get-compress-key') - -const isProductionLikeMode = options => { - return options.mode === 'production' || !options.mode -} +const { generateVariableNameBySource, isProductionLikeMode } = require('../utils/optimize-compress') module.exports = function (content) { const nativeCallback = this.async() @@ -178,32 +174,6 @@ module.exports = function (content) { } } - if (this.options.optimizeSize && isProductionLikeMode(compiler.options) && mode !== 'web') { - // placeholder 替换 - if (json.componentPlaceholder) { - const newComponentPlaceholder = {} - for (const [name, value] of Object.entries(json.componentPlaceholder)) { - const newName = generateVariableNameBySource(name, this.resourcePath + 'componentName') - newComponentPlaceholder[newName] = json.componentPlaceholder[name] - delete json.componentPlaceholder[name] - if (value in json.usingComponents) { - newComponentPlaceholder[newName] = generateVariableNameBySource(value, this.resourcePath + 'componentName') - } - } - Object.assign(json.componentPlaceholder, newComponentPlaceholder) - } - // usingComponents 替换 - if (json.usingComponents) { - const newUsingComponents = {} - for (const name of Object.keys(json.usingComponents)) { - const newName = generateVariableNameBySource(name, this.resourcePath + 'componentName') - newUsingComponents[newName] = json.usingComponents[name] - delete json.usingComponents[name] - } - Object.assign(json.usingComponents, newUsingComponents) - } - } - // 快应用补全json配置,必填项 if (mode === 'qa' && isApp) { const defaultConf = { @@ -287,6 +257,35 @@ module.exports = function (content) { } } + const processOptimizeSize = (json, callback) => { + if (mpx.optimizeSize && isProductionLikeMode(this)) { + // placeholder 替换 + if (json.componentPlaceholder) { + const newComponentPlaceholder = {} + for (const [name, value] of Object.entries(json.componentPlaceholder)) { + const newName = generateVariableNameBySource(name, this.resourcePath + 'componentName') + newComponentPlaceholder[newName] = json.componentPlaceholder[name] + delete json.componentPlaceholder[name] + if (value in json.usingComponents) { + newComponentPlaceholder[newName] = generateVariableNameBySource(value, this.resourcePath + 'componentName') + } + } + Object.assign(json.componentPlaceholder, newComponentPlaceholder) + } + // usingComponents 替换 + if (json.usingComponents) { + const newUsingComponents = {} + for (const name of Object.keys(json.usingComponents)) { + const newName = generateVariableNameBySource(name, this.resourcePath + 'componentName') + newUsingComponents[newName] = json.usingComponents[name] + delete json.usingComponents[name] + } + Object.assign(json.usingComponents, newUsingComponents) + } + } + callback() + } + if (isApp) { // app.json const localPages = [] @@ -636,6 +635,9 @@ module.exports = function (content) { } async.parallel([ + (callback) => { + processOptimizeSize(json, callback) + }, (callback) => { // 添加首页标识 if (json.pages && json.pages[0]) { @@ -714,6 +716,9 @@ module.exports = function (content) { } } async.parallel([ + (callback) => { + processOptimizeSize(json, callback) + }, (callback) => { processComponents(json.usingComponents, this.context, callback) }, diff --git a/packages/webpack-plugin/lib/template-compiler/compiler.js b/packages/webpack-plugin/lib/template-compiler/compiler.js index 0ea67b5fa5..f083585bd5 100644 --- a/packages/webpack-plugin/lib/template-compiler/compiler.js +++ b/packages/webpack-plugin/lib/template-compiler/compiler.js @@ -12,6 +12,7 @@ const transDynamicClassExpr = require('./trans-dynamic-class-expr') const dash2hump = require('../utils/hump-dash').dash2hump const makeMap = require('../utils/make-map') const { isNonPhrasingTag } = require('../utils/dom-tag-config') +const { isProductionLikeMode, generateVariableNameBySource } = require('../utils/optimize-compress') const no = function () { return false @@ -788,6 +789,10 @@ function parse (template, options) { arr.length && warn$1(`\n ${options.filePath} \n 组件 ${arr.join(' | ')} 注册了,但是未被对应的模板引用,建议删除!`) } + if (options.optimizeSize && isProductionLikeMode(this)) { + processOptimizeSize(root, options) + } + return { root, meta @@ -2213,6 +2218,33 @@ function postProcessComponentIs (el) { return el } +function processOptimizeSize (root, options) { + const { usingComponents, filePath } = options + function walkNode (root, callback) { + if (!root) return + callback(root) + if (Array.isArray(root.children) && root.children.length) { + for (const node of root.children) { + if (!node) continue + walkNode(node, callback) + } + } + } + // 记录所有原生组件(判断条件:usingComponents中不存在的组件) + const nativeTags = new Set() + walkNode(root, (node) => { + if (node.tag && usingComponents.indexOf(node.tag) === -1) { + nativeTags.add(node.tag) + } + }) + walkNode(root, (node) => { + // 只有自定义组件才替换(判断条件:在usingComponents中的组件),并且新组件名不允许出现原生组件名 + if (node.tag && usingComponents.indexOf(node.tag) !== -1) { + node.tag = generateVariableNameBySource(node.tag, filePath + 'componentName', [...nativeTags]) + } + }) +} + function stringifyAttr (val) { if (typeof val === 'string') { const hasSingle = val.indexOf('\'') > -1 diff --git a/packages/webpack-plugin/lib/template-compiler/index.js b/packages/webpack-plugin/lib/template-compiler/index.js index 0c340f374e..0e522a1c8c 100644 --- a/packages/webpack-plugin/lib/template-compiler/index.js +++ b/packages/webpack-plugin/lib/template-compiler/index.js @@ -3,11 +3,6 @@ const bindThis = require('./bind-this') const parseRequest = require('../utils/parse-request') const { matchCondition } = require('../utils/match-condition') const loaderUtils = require('loader-utils') -const { generateVariableNameBySource } = require('../utils/get-compress-key') - -const isProductionLikeMode = options => { - return options.mode === 'production' || !options.mode -} module.exports = function (raw) { this.cacheable() @@ -18,6 +13,7 @@ module.exports = function (raw) { const env = mpx.env const defs = mpx.defs const i18n = mpx.i18n + const optimizeSize = mpx.optimizeSize const externalClasses = mpx.externalClasses const decodeHTMLText = mpx.decodeHTMLText const globalSrcMode = mpx.srcMode @@ -73,39 +69,13 @@ module.exports = function (raw) { // 这里需传递resourcePath和wxsContentMap保持一致 filePath: resourcePath, i18n, + optimizeSize, checkUsingComponents: matchCondition(resourcePath, mpx.checkUsingComponentsRules), globalComponents: Object.keys(mpx.usingComponents), forceProxyEvent: matchCondition(resourcePath, mpx.forceProxyEventRules), hasVirtualHost: matchCondition(resourcePath, mpx.autoVirtualHostRules) }) - // 组件名压缩 - if (this.options.optimizeSize && isProductionLikeMode(compiler.options) && mode !== 'web') { - function walkNode (root, callback) { - if (!root) return - callback(root) - if (Array.isArray(root.children) && root.children.length) { - for (const node of root.children) { - if (!node) continue - walkNode(node, callback) - } - } - } - // 记录所有原生组件(判断条件:usingComponents中不存在的组件) - const nativeTags = new Set() - walkNode(ast, (node) => { - if (node.tag && usingComponents.indexOf(node.tag) === -1) { - nativeTags.add(node.tag) - } - }) - walkNode(ast, (node) => { - // 只有自定义组件才替换(判断条件:在usingComponents中的组件),并且新组件名不允许出现原生组件名 - if (node.tag && usingComponents.indexOf(node.tag) !== -1) { - node.tag = generateVariableNameBySource(node.tag, resourcePath + 'componentName', [...nativeTags]) - } - }) - } - if (meta.wxsContentMap) { for (const module in meta.wxsContentMap) { wxsContentMap[`${resourcePath}~${module}`] = meta.wxsContentMap[module] diff --git a/packages/webpack-plugin/lib/utils/get-compress-key.js b/packages/webpack-plugin/lib/utils/optimize-compress.js similarity index 95% rename from packages/webpack-plugin/lib/utils/get-compress-key.js rename to packages/webpack-plugin/lib/utils/optimize-compress.js index 6e3953f3df..52364be9be 100644 --- a/packages/webpack-plugin/lib/utils/get-compress-key.js +++ b/packages/webpack-plugin/lib/utils/optimize-compress.js @@ -1,6 +1,6 @@ class CompressName { constructor (chars, allowStartChars) { - this._arr = [0] + this._arr = [] // this._occupiedNames = new Set() this._compressMap = new Map() // 允许使用的字符, 需要去重 @@ -95,6 +95,11 @@ function generateVariableNameBySource (source, namespace, occupiedKey) { return namespaces[namespace].compress(source, occupiedKey) } +const isProductionLikeMode = options => { + return options.mode === 'production' || !options.mode +} + module.exports = { - generateVariableNameBySource + generateVariableNameBySource, + isProductionLikeMode } From 2757dcd1a3bb3edcb37652e698d5e96d07915efc Mon Sep 17 00:00:00 2001 From: mackwang Date: Thu, 11 Jul 2024 18:18:25 +0800 Subject: [PATCH 06/10] add --- .../webpack-plugin/lib/json-compiler/index.js | 7 +- packages/webpack-plugin/lib/loader.js | 19 +++-- .../lib/template-compiler/compiler.js | 23 +++--- .../lib/utils/optimize-compress.js | 72 +++---------------- .../webpack-plugin/lib/web/processTemplate.js | 4 +- 5 files changed, 46 insertions(+), 79 deletions(-) diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index a09db1eaba..05c6faeab3 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -44,6 +44,7 @@ module.exports = function (content) { const localSrcMode = queryObj.mode const srcMode = localSrcMode || globalSrcMode const projectRoot = mpx.projectRoot + const usingComponentsNameMap = queryObj.usingComponentsNameMap const isApp = !(pagesMap[resourcePath] || componentsMap[resourcePath]) const publicPath = this._compilation.outputOptions.publicPath || '' @@ -263,11 +264,11 @@ module.exports = function (content) { if (json.componentPlaceholder) { const newComponentPlaceholder = {} for (const [name, value] of Object.entries(json.componentPlaceholder)) { - const newName = generateVariableNameBySource(name, this.resourcePath + 'componentName') + const newName = usingComponentsNameMap[name] newComponentPlaceholder[newName] = json.componentPlaceholder[name] delete json.componentPlaceholder[name] if (value in json.usingComponents) { - newComponentPlaceholder[newName] = generateVariableNameBySource(value, this.resourcePath + 'componentName') + newComponentPlaceholder[newName] = usingComponentsNameMap[value] } } Object.assign(json.componentPlaceholder, newComponentPlaceholder) @@ -276,7 +277,7 @@ module.exports = function (content) { if (json.usingComponents) { const newUsingComponents = {} for (const name of Object.keys(json.usingComponents)) { - const newName = generateVariableNameBySource(name, this.resourcePath + 'componentName') + const newName = usingComponentsNameMap[name] newUsingComponents[newName] = json.usingComponents[name] delete json.usingComponents[name] } diff --git a/packages/webpack-plugin/lib/loader.js b/packages/webpack-plugin/lib/loader.js index 97d40ae3b9..e735c89ccf 100644 --- a/packages/webpack-plugin/lib/loader.js +++ b/packages/webpack-plugin/lib/loader.js @@ -21,6 +21,7 @@ const { MPX_APP_MODULE_ID } = require('./utils/const') const path = require('path') const processMainScript = require('./web/processMainScript') const getRulesRunner = require('./platform') +const { CompressName } = require('./utils/optimize-compress.js') module.exports = function (content) { this.cacheable() @@ -50,6 +51,7 @@ module.exports = function (content) { const localSrcMode = queryObj.mode const srcMode = localSrcMode || globalSrcMode const autoScope = matchCondition(resourcePath, mpx.autoScopeRules) + const compressName = new CompressName() const emitWarning = (msg) => { this.emitWarning( @@ -113,7 +115,11 @@ module.exports = function (content) { const hasComment = templateAttrs && templateAttrs.comments const isNative = false - let usingComponents = [].concat(Object.keys(mpx.usingComponents)) + let usingComponentsNameMap = {} + for (const name in mpx.usingComponents) { + usingComponentsNameMap[name] = name //compressName._generateName() + } + // let usingComponents = [].concat(Object.keys(mpx.usingComponents)) let componentPlaceholder = [] let componentGenerics = {} @@ -134,7 +140,10 @@ module.exports = function (content) { const ret = JSON5.parse(parts.json.content) if (rulesRunner) rulesRunner(ret) if (ret.usingComponents) { - usingComponents = usingComponents.concat(Object.keys(ret.usingComponents)) + for (const name in ret.usingComponents) { + usingComponentsNameMap[name] = compressName._generateName() + } + // usingComponents = usingComponents.concat(Object.keys(ret.usingComponents)) } if (ret.componentPlaceholder) { componentPlaceholder = componentPlaceholder.concat(Object.values(ret.componentPlaceholder)) @@ -192,7 +201,7 @@ module.exports = function (content) { srcMode, moduleId, ctorType, - usingComponents, + usingComponentsNameMap, componentGenerics }, callback) }, @@ -302,7 +311,7 @@ module.exports = function (content) { hasComment, isNative, moduleId, - usingComponents, + usingComponentsNameMap, componentPlaceholder // 添加babel处理渲染函数中可能包含的...展开运算符 // 由于...运算符应用范围极小以及babel成本极高,先关闭此特性后续看情况打开 @@ -339,7 +348,7 @@ module.exports = function (content) { output += '/* json */\n' // 给予json默认值, 确保生成json request以自动补全json const json = parts.json || {} - output += getRequire('json', json, json.src && { ...queryObj, resourcePath }) + '\n' + output += getRequire('json', json, json.src && { ...queryObj, resourcePath, usingComponentsNameMap }) + '\n' // script output += '/* script */\n' diff --git a/packages/webpack-plugin/lib/template-compiler/compiler.js b/packages/webpack-plugin/lib/template-compiler/compiler.js index f083585bd5..c1ee62a481 100644 --- a/packages/webpack-plugin/lib/template-compiler/compiler.js +++ b/packages/webpack-plugin/lib/template-compiler/compiler.js @@ -624,6 +624,7 @@ function parse (template, options) { filePath = options.filePath i18n = options.i18n refId = 0 + const usingComponents = Object.keys(options.usingComponentsNameMap) rulesRunner = getRulesRunner({ mode, @@ -631,7 +632,7 @@ function parse (template, options) { type: 'template', testKey: 'tag', data: { - usingComponents: options.usingComponents + usingComponents }, warn: _warn, error: _error @@ -781,7 +782,7 @@ function parse (template, options) { if (!tagNames.has('component') && options.checkUsingComponents) { const arr = [] - options.usingComponents.forEach((item) => { + usingComponents.forEach((item) => { if (!tagNames.has(item) && !options.globalComponents.includes(item) && !options.componentPlaceholder.includes(item)) { arr.push(item) } @@ -950,7 +951,7 @@ function processComponentIs (el, options) { } options = options || {} - el.components = options.usingComponents + el.components = Object.keys(options.usingComponentsNameMap) if (!el.components) { warn$1('Component in which tag is used must have a nonblank usingComponents field') } @@ -1666,7 +1667,7 @@ function isRealNode (el) { } function isComponentNode (el, options) { - return options.usingComponents.indexOf(el.tag) !== -1 || el.tag === 'component' + return options.usingComponentsNameMap[el.tag] || el.tag === 'component' } function processAliExternalClassesHack (el, options) { @@ -2219,7 +2220,7 @@ function postProcessComponentIs (el) { } function processOptimizeSize (root, options) { - const { usingComponents, filePath } = options + const { usingComponentsNameMap } = options function walkNode (root, callback) { if (!root) return callback(root) @@ -2233,14 +2234,20 @@ function processOptimizeSize (root, options) { // 记录所有原生组件(判断条件:usingComponents中不存在的组件) const nativeTags = new Set() walkNode(root, (node) => { - if (node.tag && usingComponents.indexOf(node.tag) === -1) { + if (node.tag && !usingComponentsNameMap[node.tag]) { nativeTags.add(node.tag) } }) + // 校验压缩后的组件名是否与原生组件冲突 + for (const name of Object.values(usingComponentsNameMap)) { + if (nativeTags.has(name)) { + error$1(`压缩后组件与原生组件 <${name}> 冲突,请在配置中添加白名单`) + } + } walkNode(root, (node) => { // 只有自定义组件才替换(判断条件:在usingComponents中的组件),并且新组件名不允许出现原生组件名 - if (node.tag && usingComponents.indexOf(node.tag) !== -1) { - node.tag = generateVariableNameBySource(node.tag, filePath + 'componentName', [...nativeTags]) + if (node.tag && usingComponentsNameMap[node.tag]) { + node.tag = usingComponentsNameMap[node.tag] } }) } diff --git a/packages/webpack-plugin/lib/utils/optimize-compress.js b/packages/webpack-plugin/lib/utils/optimize-compress.js index 52364be9be..273bfa0fa0 100644 --- a/packages/webpack-plugin/lib/utils/optimize-compress.js +++ b/packages/webpack-plugin/lib/utils/optimize-compress.js @@ -1,66 +1,16 @@ + class CompressName { - constructor (chars, allowStartChars) { - this._arr = [] - // this._occupiedNames = new Set() + constructor () { + this.index = 0 this._compressMap = new Map() - // 允许使用的字符, 需要去重 - this.chars = typeof chars === 'string' ? [...new Set(chars.split(''))].join('') : 'abcdefghijklmnopqrstuvwxyz' - // 首个字符允许的字符(生产变量名时用于指定禁止数字开头) - this.allowStartChars = [...new Set(allowStartChars.split(''))].join('') || this.chars - - // 检查一下allowStartChars必须都在char中,以防运行阶段出现死循环 - for (const char of this.allowStartChars) { - if (this.chars.indexOf(char) === -1) { - throw new Error(`CompressName allowStartChars 包含 chars 中不存在的字符: "${char}"`) - } - } - } - - // 用于获取符合首字母规则的字符的下标 - _findStartCharIndex (startIndex) { - for (let i = startIndex; i < this.chars.length; i++) { - if (this.allowStartChars.indexOf(this.chars[i]) !== -1) { - return i - } - } - return -1 } _generateName () { - if (this._arr.length === 0) { - // 首次生成,获取首字母 - this._arr[0] = this._findStartCharIndex(0) - } else { - if (this._arr.length === 1) { - // 只有一个字母,从当前位置往后获取首字母 - this._arr[0] = this._findStartCharIndex(this._arr[0] + 1) - // 如果获取不到,则直接设置到最大值,后面在来做进位处理 - if (this._arr[0] === -1) this._arr[0] = this.chars.length - } else { - // 最后一个字母(非首字母),+1即可 - this._arr[this._arr.length - 1]++ - } - - // 进位处理,如果数组中某一位 = chars.length,则前一项+1,当前项为0 - for (let i = this._arr.length - 1; i >= 0; i--) { - if (this._arr[i] === this.chars.length) { - this._arr[i] = 0 - if (i === 0) { - // 当前为第一位,则再补充一个最小的首位: [10,0] -> [1,0,0] - this._arr.unshift(this._findStartCharIndex(0)) - } else if (i === 1) { - // 当前为第二位,进位会影响首位,也需要findStartCharIndex - this._arr[i - 1] = this._findStartCharIndex(this._arr[i - 1] + 1) - if (this._arr[i - 1] === -1) this._arr[i - 1] = this.chars.length - } else { - // 其他情况,正常进位即可 - this._arr[i - 1]++ - } - } - } - } - // 获取每一位对应的字符拼接 - return this._arr.map(num => this.chars[num]).join('') + let name = this.index.toString(36) + // 首字母不能是数字(转化为number不是NaN就是数字) + if (!isNaN(+name[0])) name = 'a' + name.substring(1) + this.index = parseInt(name, 36) + 1 + return name } // 指定不允许使用的key @@ -80,7 +30,6 @@ class CompressName { compress (source, occupiedKey) { if (!this._compressMap.has(source)) { this._compressMap.set(source, this._occupiedGenerateName(occupiedKey)) - // this._occupiedNames.add(this._compressMap.get(source)) } return this._compressMap.get(source) } @@ -90,7 +39,7 @@ const namespaces = {} function generateVariableNameBySource (source, namespace, occupiedKey) { if (!namespaces[namespace]) { // 限制只能字母开头 - namespaces[namespace] = new CompressName('abcdefghijklmnopqrstuvwxyz_0123456789', 'abcdefghijklmnopqrstuvwxyz') + namespaces[namespace] = new CompressName() } return namespaces[namespace].compress(source, occupiedKey) } @@ -101,5 +50,6 @@ const isProductionLikeMode = options => { module.exports = { generateVariableNameBySource, - isProductionLikeMode + isProductionLikeMode, + CompressName } diff --git a/packages/webpack-plugin/lib/web/processTemplate.js b/packages/webpack-plugin/lib/web/processTemplate.js index a3f69d76f8..2f89b3bd70 100644 --- a/packages/webpack-plugin/lib/web/processTemplate.js +++ b/packages/webpack-plugin/lib/web/processTemplate.js @@ -12,7 +12,7 @@ module.exports = function (template, { srcMode, moduleId, ctorType, - usingComponents, + usingComponentsNameMap, componentGenerics }, callback) { const mpx = loaderContext.getMpx() @@ -72,7 +72,7 @@ module.exports = function (template, { new Error('[template compiler][' + loaderContext.resource + ']: ' + msg) ) }, - usingComponents, + usingComponentsNameMap, hasComment, isNative, isComponent: ctorType === 'component', From 485034fd172cca99a43dab68041d088f0be0b79a Mon Sep 17 00:00:00 2001 From: mackwang Date: Mon, 29 Jul 2024 10:35:33 +0800 Subject: [PATCH 07/10] =?UTF-8?q?fix:=20=E8=B0=83=E6=95=B4=E5=8E=8B?= =?UTF-8?q?=E7=BC=A9=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../webpack-plugin/lib/json-compiler/index.js | 2 +- packages/webpack-plugin/lib/loader.js | 15 ++++++++++----- .../lib/template-compiler/compiler.js | 1 + .../webpack-plugin/lib/template-compiler/index.js | 4 ++-- 4 files changed, 14 insertions(+), 8 deletions(-) diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index 05c6faeab3..0d5f015fe5 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -44,7 +44,7 @@ module.exports = function (content) { const localSrcMode = queryObj.mode const srcMode = localSrcMode || globalSrcMode const projectRoot = mpx.projectRoot - const usingComponentsNameMap = queryObj.usingComponentsNameMap + const usingComponentsNameMap = JSON.parse(queryObj.usingComponentsNameMap) const isApp = !(pagesMap[resourcePath] || componentsMap[resourcePath]) const publicPath = this._compilation.outputOptions.publicPath || '' diff --git a/packages/webpack-plugin/lib/loader.js b/packages/webpack-plugin/lib/loader.js index e735c89ccf..2a2eab4433 100644 --- a/packages/webpack-plugin/lib/loader.js +++ b/packages/webpack-plugin/lib/loader.js @@ -119,7 +119,6 @@ module.exports = function (content) { for (const name in mpx.usingComponents) { usingComponentsNameMap[name] = name //compressName._generateName() } - // let usingComponents = [].concat(Object.keys(mpx.usingComponents)) let componentPlaceholder = [] let componentGenerics = {} @@ -141,9 +140,9 @@ module.exports = function (content) { if (rulesRunner) rulesRunner(ret) if (ret.usingComponents) { for (const name in ret.usingComponents) { - usingComponentsNameMap[name] = compressName._generateName() + // 压缩组件名,禁止与全局组件同名 + usingComponentsNameMap[name] = ctorType === 'app' ? name : compressName._occupiedGenerateName([...mpx.usingComponents]) } - // usingComponents = usingComponents.concat(Object.keys(ret.usingComponents)) } if (ret.componentPlaceholder) { componentPlaceholder = componentPlaceholder.concat(Object.values(ret.componentPlaceholder)) @@ -311,7 +310,7 @@ module.exports = function (content) { hasComment, isNative, moduleId, - usingComponentsNameMap, + usingComponentsNameMap: JSON.stringify(usingComponentsNameMap), componentPlaceholder // 添加babel处理渲染函数中可能包含的...展开运算符 // 由于...运算符应用范围极小以及babel成本极高,先关闭此特性后续看情况打开 @@ -348,7 +347,13 @@ module.exports = function (content) { output += '/* json */\n' // 给予json默认值, 确保生成json request以自动补全json const json = parts.json || {} - output += getRequire('json', json, json.src && { ...queryObj, resourcePath, usingComponentsNameMap }) + '\n' + output += getRequire('json', json, { + ...(json.src ? { + ...queryObj, + resourcePath + } : null), + usingComponentsNameMap: JSON.stringify(usingComponentsNameMap) + }) + '\n' // script output += '/* script */\n' diff --git a/packages/webpack-plugin/lib/template-compiler/compiler.js b/packages/webpack-plugin/lib/template-compiler/compiler.js index c1ee62a481..9a48ec532c 100644 --- a/packages/webpack-plugin/lib/template-compiler/compiler.js +++ b/packages/webpack-plugin/lib/template-compiler/compiler.js @@ -624,6 +624,7 @@ function parse (template, options) { filePath = options.filePath i18n = options.i18n refId = 0 + options.usingComponentsNameMap = options.usingComponentsNameMap || {} const usingComponents = Object.keys(options.usingComponentsNameMap) rulesRunner = getRulesRunner({ diff --git a/packages/webpack-plugin/lib/template-compiler/index.js b/packages/webpack-plugin/lib/template-compiler/index.js index 0e522a1c8c..83423f584f 100644 --- a/packages/webpack-plugin/lib/template-compiler/index.js +++ b/packages/webpack-plugin/lib/template-compiler/index.js @@ -23,7 +23,7 @@ module.exports = function (raw) { const pagesMap = mpx.pagesMap const wxsContentMap = mpx.wxsContentMap const optimizeRenderRules = mpx.optimizeRenderRules - const usingComponents = queryObj.usingComponents || [] + const usingComponentsNameMap = JSON.parse(queryObj.usingComponentsNameMap) const componentPlaceholder = queryObj.componentPlaceholder || [] const hasComment = queryObj.hasComment const isNative = queryObj.isNative @@ -52,7 +52,7 @@ module.exports = function (raw) { const { root: ast, meta } = compiler.parse(raw, { warn, error, - usingComponents, + usingComponentsNameMap, componentPlaceholder, hasComment, isNative, From c67de079f4143a2c959750378a60bf18eb89266d Mon Sep 17 00:00:00 2001 From: mackwang Date: Mon, 29 Jul 2024 15:55:58 +0800 Subject: [PATCH 08/10] =?UTF-8?q?fix:=20=E8=B0=83=E6=95=B4=E5=8E=8B?= =?UTF-8?q?=E7=BC=A9=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/webpack-plugin/lib/index.js | 6 ++++++ packages/webpack-plugin/lib/loader.js | 5 +++-- packages/webpack-plugin/lib/template-compiler/compiler.js | 2 ++ packages/webpack-plugin/lib/template-compiler/index.js | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/packages/webpack-plugin/lib/index.js b/packages/webpack-plugin/lib/index.js index 8f9acc9494..8b520d4786 100644 --- a/packages/webpack-plugin/lib/index.js +++ b/packages/webpack-plugin/lib/index.js @@ -171,6 +171,11 @@ class MpxWebpackPlugin { options.optimizeRenderRules = options.optimizeRenderRules ? (Array.isArray(options.optimizeRenderRules) ? options.optimizeRenderRules : [options.optimizeRenderRules]) : [] options.retryRequireAsync = options.retryRequireAsync || false options.optimizeSize = options.optimizeSize || false + // 保留组件名(压缩后组件名不允许出现) + if (typeof options.reservedComponentName === 'object') { + options.reservedComponentName = options.reservedComponentName[options.mode] + } + options.reservedComponentName = options.reservedComponentName || [] this.options = options // Hack for buildDependencies const rawResolveBuildDependencies = FileSystemInfo.prototype.resolveBuildDependencies @@ -668,6 +673,7 @@ class MpxWebpackPlugin { asyncSubpackageRules: this.options.asyncSubpackageRules, optimizeRenderRules: this.options.optimizeRenderRules, optimizeSize: this.options.optimizeSize, + reservedComponentName: this.options.reservedComponentName, pathHash: (resourcePath) => { if (this.options.pathHashMode === 'relative' && this.options.projectRoot) { return hash(path.relative(this.options.projectRoot, resourcePath)) diff --git a/packages/webpack-plugin/lib/loader.js b/packages/webpack-plugin/lib/loader.js index 2a2eab4433..061edf6615 100644 --- a/packages/webpack-plugin/lib/loader.js +++ b/packages/webpack-plugin/lib/loader.js @@ -140,8 +140,9 @@ module.exports = function (content) { if (rulesRunner) rulesRunner(ret) if (ret.usingComponents) { for (const name in ret.usingComponents) { - // 压缩组件名,禁止与全局组件同名 - usingComponentsNameMap[name] = ctorType === 'app' ? name : compressName._occupiedGenerateName([...mpx.usingComponents]) + // Object.keys(mpx.usingComponents): 压缩组件名,禁止与全局组件同名 + // mpx.reservedComponentName 禁止与保留组件名重复(如 text/view/ad 等) + usingComponentsNameMap[name] = ctorType === 'app' ? name : compressName._occupiedGenerateName([...Object.keys(mpx.usingComponents), ...mpx.reservedComponentName]) } } if (ret.componentPlaceholder) { diff --git a/packages/webpack-plugin/lib/template-compiler/compiler.js b/packages/webpack-plugin/lib/template-compiler/compiler.js index 9a48ec532c..015912390c 100644 --- a/packages/webpack-plugin/lib/template-compiler/compiler.js +++ b/packages/webpack-plugin/lib/template-compiler/compiler.js @@ -2239,6 +2239,8 @@ function processOptimizeSize (root, options) { nativeTags.add(node.tag) } }) + // template中的使用到的组件不会经过压缩,如果使用自定义组件会出现问题,如果存在template,发出报错 + if (nativeTags.has('template')) error$1(`使用template模板无法开启组件名压缩`) // 校验压缩后的组件名是否与原生组件冲突 for (const name of Object.values(usingComponentsNameMap)) { if (nativeTags.has(name)) { diff --git a/packages/webpack-plugin/lib/template-compiler/index.js b/packages/webpack-plugin/lib/template-compiler/index.js index 83423f584f..a39151fe47 100644 --- a/packages/webpack-plugin/lib/template-compiler/index.js +++ b/packages/webpack-plugin/lib/template-compiler/index.js @@ -23,7 +23,7 @@ module.exports = function (raw) { const pagesMap = mpx.pagesMap const wxsContentMap = mpx.wxsContentMap const optimizeRenderRules = mpx.optimizeRenderRules - const usingComponentsNameMap = JSON.parse(queryObj.usingComponentsNameMap) + const usingComponentsNameMap = JSON.parse(queryObj.usingComponentsNameMap || "{}") const componentPlaceholder = queryObj.componentPlaceholder || [] const hasComment = queryObj.hasComment const isNative = queryObj.isNative From e725d75ca8c1382537e424a7e991bc005f8712dc Mon Sep 17 00:00:00 2001 From: xuegan Date: Tue, 12 Nov 2024 17:20:34 +0800 Subject: [PATCH 09/10] =?UTF-8?q?feat:=20=E4=BA=8C=E6=AC=A1=E7=AE=80?= =?UTF-8?q?=E5=8C=96global=E6=8C=82=E5=9C=A8=E5=B1=9E=E6=80=A7=E9=95=BF?= =?UTF-8?q?=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/core/src/core/transferOptions.js | 8 ++++---- packages/core/src/platform/createApp.js | 4 ++-- packages/core/src/platform/patch/index.js | 4 ++-- packages/webpack-plugin/lib/loader.js | 4 ++-- packages/webpack-plugin/lib/native-loader.js | 4 ++-- .../webpack-plugin/lib/template-compiler/index.js | 12 ++++++------ packages/webpack-plugin/lib/web/script-helper.js | 8 ++++---- 7 files changed, 22 insertions(+), 22 deletions(-) diff --git a/packages/core/src/core/transferOptions.js b/packages/core/src/core/transferOptions.js index 26b2f76ba9..a39c94cebd 100644 --- a/packages/core/src/core/transferOptions.js +++ b/packages/core/src/core/transferOptions.js @@ -5,10 +5,10 @@ import { warn, findItem } from '@mpxjs/utils' export default function transferOptions (options, type, needConvert = true) { let currentInject - // currentModuleId -> _mid - // currentInject -> _cj - if (global._cj && global._cj.moduleId === global._mid) { - currentInject = global._cj + // currentModuleId -> _id + // currentInject -> _j + if (global._j && global._j.moduleId === global._id) { + currentInject = global._j } // 文件编译路径 options.mpxFileResource = global.currentResource diff --git a/packages/core/src/platform/createApp.js b/packages/core/src/platform/createApp.js index b47748ef38..978b3ab4d2 100644 --- a/packages/core/src/platform/createApp.js +++ b/packages/core/src/platform/createApp.js @@ -82,8 +82,8 @@ export default function createApp (option, config = {}) { if (__mpx_mode__ === 'web') { global.__mpxOptionsMap = global.__mpxOptionsMap || {} - // currentModuleId -> _mid - global.__mpxOptionsMap[global._mid] = defaultOptions + // currentModuleId -> _id + global.__mpxOptionsMap[global._id] = defaultOptions global.getApp = function () { if (!isBrowser) { console.error('[Mpx runtime error]: Dangerous API! global.getApp method is running in non browser environments') diff --git a/packages/core/src/platform/patch/index.js b/packages/core/src/platform/patch/index.js index ca09841873..a350949c36 100644 --- a/packages/core/src/platform/patch/index.js +++ b/packages/core/src/platform/patch/index.js @@ -62,8 +62,8 @@ export default function createFactory (type) { const defaultOptions = getDefaultOptions(type, { rawOptions, currentInject }) if (__mpx_mode__ === 'web') { global.__mpxOptionsMap = global.__mpxOptionsMap || {} - // currentModuleId -> _mid - global.__mpxOptionsMap[global._mid] = defaultOptions + // currentModuleId -> _id + global.__mpxOptionsMap[global._id] = defaultOptions } else if (ctor) { return ctor(defaultOptions) } diff --git a/packages/webpack-plugin/lib/loader.js b/packages/webpack-plugin/lib/loader.js index 061edf6615..7f2ebfda3f 100644 --- a/packages/webpack-plugin/lib/loader.js +++ b/packages/webpack-plugin/lib/loader.js @@ -258,8 +258,8 @@ module.exports = function (content) { } // 注入模块id及资源路径 - // currentModuleId -> _mid - output += `global._mid = ${JSON.stringify(moduleId)}\n` + // currentModuleId -> _id + output += `global._id = ${JSON.stringify(moduleId)}\n` if (!isProduction) { output += `global.currentResource = ${JSON.stringify(filePath)}\n` } diff --git a/packages/webpack-plugin/lib/native-loader.js b/packages/webpack-plugin/lib/native-loader.js index d2c63ee3e6..a4510dd6a2 100644 --- a/packages/webpack-plugin/lib/native-loader.js +++ b/packages/webpack-plugin/lib/native-loader.js @@ -241,8 +241,8 @@ module.exports = function (content) { } // 注入模块id及资源路径 - // currentModuleId -> _mid - let output = `global._mid = ${JSON.stringify(moduleId)}\n` + // currentModuleId -> _id + let output = `global._id = ${JSON.stringify(moduleId)}\n` if (!isProduction) { output += `global.currentResource = ${JSON.stringify(filePath)}\n` } diff --git a/packages/webpack-plugin/lib/template-compiler/index.js b/packages/webpack-plugin/lib/template-compiler/index.js index a39151fe47..bc718adf13 100644 --- a/packages/webpack-plugin/lib/template-compiler/index.js +++ b/packages/webpack-plugin/lib/template-compiler/index.js @@ -94,9 +94,9 @@ module.exports = function (raw) { const src = loaderUtils.urlToRequest(meta.wxsModuleMap[module], root) resultSource += `var ${module} = require(${loaderUtils.stringifyRequest(this, src)});\n` } - // currentInject -> _cj + // currentInject -> _j resultSource += ` -global._cj = { +global._j = { moduleId: ${JSON.stringify(moduleId)} };\n` @@ -119,7 +119,7 @@ global._cj = { ignoreMap }) resultSource += ` -global._cj.render = function (_i, _c, _r, _sc) { +global._j.render = function (_i, _c, _r, _sc) { ${bindResult.code} _r(${optimizeRenderLevel === 2 ? 'true' : ''}); };\n` @@ -141,20 +141,20 @@ ${e.stack}`) if (meta.computed) { resultSource += bindThis.transform(` -global._cj.injectComputed = { +global._j.injectComputed = { ${meta.computed.join(',')} };`).code + '\n' } if (meta.refs) { resultSource += ` -global._cj.getRefsData = function () { +global._j.getRefsData = function () { return ${JSON.stringify(meta.refs)}; };\n` } if (meta.options) { - resultSource += `global._cj.injectOptions = ${JSON.stringify(meta.options)};` + '\n' + resultSource += `global._j.injectOptions = ${JSON.stringify(meta.options)};` + '\n' } this.emitFile(resourcePath, '', undefined, { diff --git a/packages/webpack-plugin/lib/web/script-helper.js b/packages/webpack-plugin/lib/web/script-helper.js index 6f27a31b71..679a4f9c6b 100644 --- a/packages/webpack-plugin/lib/web/script-helper.js +++ b/packages/webpack-plugin/lib/web/script-helper.js @@ -182,12 +182,12 @@ function buildGlobalParams ({ global.__mpxOptionsMap = global.__mpxOptionsMap || {} global.__mpxTransRpxFn = ${webConfig.transRpxFn} \n` } - // currentModuleId -> _mid - content += ` global._mid = ${JSON.stringify(moduleId)}\n` + // currentModuleId -> _id + content += ` global._id = ${JSON.stringify(moduleId)}\n` // currentSrcMode -> _sm content += ` global._sm = ${JSON.stringify(scriptSrcMode)}\n` - // currentInject -> _cj - content += ` global._cj = ${JSON.stringify({ moduleId })}\n` + // currentInject -> _j + content += ` global._j = ${JSON.stringify({ moduleId })}\n` if (!isProduction) { content += ` global.currentResource = ${JSON.stringify(loaderContext.resourcePath)}\n` } From 4647c4d1493ee28dea99c06f37e18395e69cfe9f Mon Sep 17 00:00:00 2001 From: mackwang Date: Tue, 12 Nov 2024 18:37:51 +0800 Subject: [PATCH 10/10] style: fix eslint --- packages/webpack-plugin/lib/json-compiler/index.js | 2 +- packages/webpack-plugin/lib/loader.js | 11 +++++------ .../webpack-plugin/lib/template-compiler/compiler.js | 4 ++-- .../webpack-plugin/lib/template-compiler/index.js | 2 +- 4 files changed, 9 insertions(+), 10 deletions(-) diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index 0d5f015fe5..a8be61e18c 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -18,7 +18,7 @@ const resolveTabBarPath = require('../utils/resolve-tab-bar-path') const normalize = require('../utils/normalize') const mpxViewPath = normalize.lib('runtime/components/ali/mpx-view.mpx') const mpxTextPath = normalize.lib('runtime/components/ali/mpx-text.mpx') -const { generateVariableNameBySource, isProductionLikeMode } = require('../utils/optimize-compress') +const { isProductionLikeMode } = require('../utils/optimize-compress') module.exports = function (content) { const nativeCallback = this.async() diff --git a/packages/webpack-plugin/lib/loader.js b/packages/webpack-plugin/lib/loader.js index 7f2ebfda3f..a0fafed5e0 100644 --- a/packages/webpack-plugin/lib/loader.js +++ b/packages/webpack-plugin/lib/loader.js @@ -115,9 +115,9 @@ module.exports = function (content) { const hasComment = templateAttrs && templateAttrs.comments const isNative = false - let usingComponentsNameMap = {} + const usingComponentsNameMap = {} for (const name in mpx.usingComponents) { - usingComponentsNameMap[name] = name //compressName._generateName() + usingComponentsNameMap[name] = name // compressName._generateName() } let componentPlaceholder = [] let componentGenerics = {} @@ -349,10 +349,9 @@ module.exports = function (content) { // 给予json默认值, 确保生成json request以自动补全json const json = parts.json || {} output += getRequire('json', json, { - ...(json.src ? { - ...queryObj, - resourcePath - } : null), + ...(json.src + ? { ...queryObj, resourcePath } + : null), usingComponentsNameMap: JSON.stringify(usingComponentsNameMap) }) + '\n' diff --git a/packages/webpack-plugin/lib/template-compiler/compiler.js b/packages/webpack-plugin/lib/template-compiler/compiler.js index 015912390c..35e6c9dfe5 100644 --- a/packages/webpack-plugin/lib/template-compiler/compiler.js +++ b/packages/webpack-plugin/lib/template-compiler/compiler.js @@ -12,7 +12,7 @@ const transDynamicClassExpr = require('./trans-dynamic-class-expr') const dash2hump = require('../utils/hump-dash').dash2hump const makeMap = require('../utils/make-map') const { isNonPhrasingTag } = require('../utils/dom-tag-config') -const { isProductionLikeMode, generateVariableNameBySource } = require('../utils/optimize-compress') +const { isProductionLikeMode } = require('../utils/optimize-compress') const no = function () { return false @@ -2240,7 +2240,7 @@ function processOptimizeSize (root, options) { } }) // template中的使用到的组件不会经过压缩,如果使用自定义组件会出现问题,如果存在template,发出报错 - if (nativeTags.has('template')) error$1(`使用template模板无法开启组件名压缩`) + if (nativeTags.has('template')) error$1('使用template模板无法开启组件名压缩') // 校验压缩后的组件名是否与原生组件冲突 for (const name of Object.values(usingComponentsNameMap)) { if (nativeTags.has(name)) { diff --git a/packages/webpack-plugin/lib/template-compiler/index.js b/packages/webpack-plugin/lib/template-compiler/index.js index bc718adf13..63a34f3e02 100644 --- a/packages/webpack-plugin/lib/template-compiler/index.js +++ b/packages/webpack-plugin/lib/template-compiler/index.js @@ -23,7 +23,7 @@ module.exports = function (raw) { const pagesMap = mpx.pagesMap const wxsContentMap = mpx.wxsContentMap const optimizeRenderRules = mpx.optimizeRenderRules - const usingComponentsNameMap = JSON.parse(queryObj.usingComponentsNameMap || "{}") + const usingComponentsNameMap = queryObj.usingComponentsNameMap ? JSON.parse(queryObj.usingComponentsNameMap) : {} const componentPlaceholder = queryObj.componentPlaceholder || [] const hasComment = queryObj.hasComment const isNative = queryObj.isNative