From 0a2a5790ba8d67bb9d0b894dae194c26653f6f5b Mon Sep 17 00:00:00 2001 From: xuegan Date: Fri, 4 Aug 2023 14:01:42 +0800 Subject: [PATCH 01/59] =?UTF-8?q?fix:=E4=BF=AE=E6=94=B9config=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs-vuepress/api/app-config.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/docs-vuepress/api/app-config.md b/docs-vuepress/api/app-config.md index 80ca27d206..97dea9bf7a 100644 --- a/docs-vuepress/api/app-config.md +++ b/docs-vuepress/api/app-config.md @@ -155,3 +155,27 @@ mpx.config.webRouteConfig = { mode: 'history' } ``` + +## errorHandler +- **类型**: `Function` + +- **默认值**:`null` + +- **用法**: + +```js +mpx.config.errorHandler = function (errmsg, location, error) { + // errmsg: 框架内部运行报错的报错归类信息,例如当执行一个watch方法报错时,会是 "Unhandled error occurs during execution of watch callback!" + // location: 具体报错的代码路径,可选项,不一定存在 + // error: 具体的错误堆栈,可选项,不一定存在 + // handle error +} +``` + +Mpx 框架运行时报错捕获感知处理函数。 + +* Mpx 框架生命周期执行错误; +* Mpx 中的 computed、watch 等响应性执行报错; +* Mpx 框架的运行时的检测报错,例如存在目标平台不支持的属性,属性类型不对; + +同时被捕获的错误会通过 console.error 输出。 From 321365fabe5f63b083827f450a297424dd88af5c Mon Sep 17 00:00:00 2001 From: xuegan Date: Sat, 5 Aug 2023 16:48:34 +0800 Subject: [PATCH 02/59] =?UTF-8?q?feat:partial=E6=9E=84=E5=BB=BA=E6=97=B6?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=3Fresolve=E6=8A=A5=E9=94=99=E8=BF=87?= =?UTF-8?q?=E6=BB=A4=E6=9C=BA=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs-vuepress/api/app-config.md | 4 +-- .../lib/dependencies/ResolveDependency.js | 13 ++++++- packages/webpack-plugin/lib/index.js | 29 +++++++++++++-- .../lib/partial-compile/index.js | 35 ------------------- 4 files changed, 41 insertions(+), 40 deletions(-) delete mode 100644 packages/webpack-plugin/lib/partial-compile/index.js diff --git a/docs-vuepress/api/app-config.md b/docs-vuepress/api/app-config.md index 97dea9bf7a..b1c546592e 100644 --- a/docs-vuepress/api/app-config.md +++ b/docs-vuepress/api/app-config.md @@ -175,7 +175,7 @@ mpx.config.errorHandler = function (errmsg, location, error) { Mpx 框架运行时报错捕获感知处理函数。 * Mpx 框架生命周期执行错误; -* Mpx 中的 computed、watch 等响应性执行报错; -* Mpx 框架的运行时的检测报错,例如存在目标平台不支持的属性,属性类型不对; +* Mpx 中的 computed、watch 等内置方法执行报错; +* Mpx 框架的运行时的检测报错,例如存在目标平台不支持的属性,入参出参类型错误等; 同时被捕获的错误会通过 console.error 输出。 diff --git a/packages/webpack-plugin/lib/dependencies/ResolveDependency.js b/packages/webpack-plugin/lib/dependencies/ResolveDependency.js index 9ae4d38ddc..b736ffcf19 100644 --- a/packages/webpack-plugin/lib/dependencies/ResolveDependency.js +++ b/packages/webpack-plugin/lib/dependencies/ResolveDependency.js @@ -35,6 +35,15 @@ class ResolveDependency extends NullDependency { return pagesMap[resourcePath] || currentComponentsMap[resourcePath] || mainComponentsMap[resourcePath] || currentStaticResourcesMap[resourcePath] || mainStaticResourcesMap[resourcePath] || '' } + isPartialCompileFilteredPage(resource) { + const { compilation } = this + if (!compilation) return '' + const mpx = compilation.__mpx__ + const { partialCompileFilteredPagesMap } = mpx + const { resourcePath } = parseRequest(resource) + return partialCompileFilteredPagesMap[resourcePath] + } + // resolved可能会动态变更,需用此更新hash updateHash (hash, context) { this.resolved = this.getResolved() @@ -42,7 +51,9 @@ class ResolveDependency extends NullDependency { if (this.resolved) { hash.update(this.resolved) } else { - compilation.errors.push(new Error(`Path ${resource} is not a page/component/static resource, which is resolved from ${issuerResource}!`)) + if (!this.isPartialCompileFilteredPage(resource)) { + compilation.errors.push(new Error(`Path ${resource} is not a page/component/static resource, which is resolved from ${issuerResource}!`)) + } } super.updateHash(hash, context) } diff --git a/packages/webpack-plugin/lib/index.js b/packages/webpack-plugin/lib/index.js index 2a816d3329..40f4c13f14 100644 --- a/packages/webpack-plugin/lib/index.js +++ b/packages/webpack-plugin/lib/index.js @@ -38,7 +38,6 @@ const FlagPluginDependency = require('./dependencies/FlagPluginDependency') const RemoveEntryDependency = require('./dependencies/RemoveEntryDependency') const RecordVueContentDependency = require('./dependencies/RecordVueContentDependency') const SplitChunksPlugin = require('webpack/lib/optimize/SplitChunksPlugin') -const PartialCompilePlugin = require('./partial-compile/index') const fixRelative = require('./utils/fix-relative') const parseRequest = require('./utils/parse-request') const { matchCondition } = require('./utils/match-condition') @@ -55,6 +54,7 @@ const jsonThemeCompilerPath = normalize.lib('json-compiler/theme') const jsonPluginCompilerPath = normalize.lib('json-compiler/plugin') const extractorPath = normalize.lib('extractor') const async = require('async') +const { parseQuery } = require('loader-utils') const stringifyLoadersAndResource = require('./utils/stringify-loaders-resource') const emitFile = require('./utils/emit-file') const { MPX_PROCESSED_FLAG, MPX_DISABLE_EXTRACTOR_CACHE } = require('./utils/const') @@ -381,7 +381,31 @@ class MpxWebpackPlugin { let mpx if (this.options.partialCompile) { - new PartialCompilePlugin(this.options.partialCompile).apply(compiler) + function isResolvingPage (obj) { + // valid query should start with '?' + const query = obj.query || '?' + return parseQuery(query).isPage + } + // new PartialCompilePlugin(this.options.partialCompile).apply(compiler) + compiler.resolverFactory.hooks.resolver.intercept({ + factory: (type, hook) => { + hook.tap('MpxPartialCompilePlugin', (resolver) => { + resolver.hooks.result.tapAsync({ + name: 'MpxPartialCompilePlugin', + stage: -100 + }, (obj, resolverContext, callback) => { + if (isResolvingPage(obj) && !matchCondition(obj.path, this.options.partialCompile)) { + mpx? mpx.partialCompileFilteredPagesMap[obj.path] = true : null + obj.path = false + + console.log('mpx', mpx) + } + callback(null, obj) + }) + }) + return hook + } + }) } const getPackageCacheGroup = packageName => { @@ -595,6 +619,7 @@ class MpxWebpackPlugin { removedChunks: [], forceProxyEventRules: this.options.forceProxyEventRules, enableRequireAsync: this.options.mode === 'wx' || (this.options.mode === 'ali' && this.options.enableAliRequireAsync), + partialCompileFilteredPagesMap: {}, 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/partial-compile/index.js b/packages/webpack-plugin/lib/partial-compile/index.js deleted file mode 100644 index 3896e74558..0000000000 --- a/packages/webpack-plugin/lib/partial-compile/index.js +++ /dev/null @@ -1,35 +0,0 @@ -const { matchCondition } = require('../utils/match-condition') -const { parseQuery } = require('loader-utils') - -class MpxPartialCompilePlugin { - constructor (condition) { - this.condition = condition - } - - isResolvingPage (obj) { - // valid query should start with '?' - const query = obj.query || '?' - return parseQuery(query).isPage - } - - apply (compiler) { - compiler.resolverFactory.hooks.resolver.intercept({ - factory: (type, hook) => { - hook.tap('MpxPartialCompilePlugin', (resolver) => { - resolver.hooks.result.tapAsync({ - name: 'MpxPartialCompilePlugin', - stage: -100 - }, (obj, resolverContext, callback) => { - if (this.isResolvingPage(obj) && !matchCondition(obj.path, this.condition)) { - obj.path = false - } - callback(null, obj) - }) - }) - return hook - } - }) - } -} - -module.exports = MpxPartialCompilePlugin From 2a06796aeb72275d9c99711814d081a1bfe7fbb3 Mon Sep 17 00:00:00 2001 From: xuegan Date: Mon, 7 Aug 2023 11:15:37 +0800 Subject: [PATCH 03/59] fix:eslint error --- packages/webpack-plugin/lib/dependencies/ResolveDependency.js | 2 +- packages/webpack-plugin/lib/index.js | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/webpack-plugin/lib/dependencies/ResolveDependency.js b/packages/webpack-plugin/lib/dependencies/ResolveDependency.js index b736ffcf19..09cdf1edb3 100644 --- a/packages/webpack-plugin/lib/dependencies/ResolveDependency.js +++ b/packages/webpack-plugin/lib/dependencies/ResolveDependency.js @@ -35,7 +35,7 @@ class ResolveDependency extends NullDependency { return pagesMap[resourcePath] || currentComponentsMap[resourcePath] || mainComponentsMap[resourcePath] || currentStaticResourcesMap[resourcePath] || mainStaticResourcesMap[resourcePath] || '' } - isPartialCompileFilteredPage(resource) { + isPartialCompileFilteredPage (resource) { const { compilation } = this if (!compilation) return '' const mpx = compilation.__mpx__ diff --git a/packages/webpack-plugin/lib/index.js b/packages/webpack-plugin/lib/index.js index 40f4c13f14..cb8f8e798b 100644 --- a/packages/webpack-plugin/lib/index.js +++ b/packages/webpack-plugin/lib/index.js @@ -395,10 +395,8 @@ class MpxWebpackPlugin { stage: -100 }, (obj, resolverContext, callback) => { if (isResolvingPage(obj) && !matchCondition(obj.path, this.options.partialCompile)) { - mpx? mpx.partialCompileFilteredPagesMap[obj.path] = true : null + if (mpx) mpx.partialCompileFilteredPagesMap[obj.path] = true obj.path = false - - console.log('mpx', mpx) } callback(null, obj) }) From 664dda943b56033bcc0fc8f9ff387135f4f9433c Mon Sep 17 00:00:00 2001 From: xuegan Date: Thu, 10 Aug 2023 01:59:06 +0800 Subject: [PATCH 04/59] =?UTF-8?q?feat:=E6=B7=BB=E5=8A=A0=E5=B1=80=E9=83=A8?= =?UTF-8?q?=E6=9E=84=E5=BB=BA=E5=85=9C=E5=BA=95=E9=A1=B5=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../webpack-plugin/lib/json-compiler/default-page.mpx | 3 +++ packages/webpack-plugin/lib/json-compiler/helper.js | 11 ++++++++++- packages/webpack-plugin/lib/json-compiler/index.js | 8 +++----- 3 files changed, 16 insertions(+), 6 deletions(-) create mode 100644 packages/webpack-plugin/lib/json-compiler/default-page.mpx diff --git a/packages/webpack-plugin/lib/json-compiler/default-page.mpx b/packages/webpack-plugin/lib/json-compiler/default-page.mpx new file mode 100644 index 0000000000..c3d015dc4d --- /dev/null +++ b/packages/webpack-plugin/lib/json-compiler/default-page.mpx @@ -0,0 +1,3 @@ + diff --git a/packages/webpack-plugin/lib/json-compiler/helper.js b/packages/webpack-plugin/lib/json-compiler/helper.js index 6a2d2b7ebe..77f8b597a3 100644 --- a/packages/webpack-plugin/lib/json-compiler/helper.js +++ b/packages/webpack-plugin/lib/json-compiler/helper.js @@ -6,6 +6,7 @@ const parseRequest = require('../utils/parse-request') const addQuery = require('../utils/add-query') const loaderUtils = require('loader-utils') const resolve = require('../utils/resolve') +const { RESOLVE_IGNORED_ERR } = require('../utils/const') module.exports = function createJSONHelper ({ loaderContext, emitWarning, customGetDynamicEntry }) { const mpx = loaderContext.getMpx() @@ -101,7 +102,15 @@ module.exports = function createJSONHelper ({ loaderContext, emitWarning, custom // 增加 page 标识 page = addQuery(page, { isPage: true }) resolve(context, page, loaderContext, (err, resource) => { - if (err) return callback(err) + if (err) { + if (err === RESOLVE_IGNORED_ERR && tarRoot) { + const defaultPage = require.resolve('./default-page.mpx') + `?resourcePath=${context}/${tarRoot}/pages/index.mpx` + resource = defaultPage + aliasPath = '' + } else { + return callback(err) + } + } const { resourcePath, queryObj: { isFirst } } = parseRequest(resource) const ext = path.extname(resourcePath) let outputPath diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index 445b955d92..3c31fe4d06 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -577,12 +577,10 @@ module.exports = function (content) { for (const root in subPackagesCfg) { const subPackageCfg = subPackagesCfg[root] // 分包不存在 pages,输出 subPackages 字段会报错 - if (subPackageCfg.pages.length) { - if (!json.subPackages) { - json.subPackages = [] - } - json.subPackages.push(subPackageCfg) + if (!json.subPackages) { + json.subPackages = [] } + json.subPackages.push(subPackageCfg) } const processOutput = (output) => { output = processDynamicEntry(output) From 03d5373a8526f23e00f05917aaf84f6fbb7ef98f Mon Sep 17 00:00:00 2001 From: xuegan Date: Thu, 10 Aug 2023 13:51:34 +0800 Subject: [PATCH 05/59] v2.8.40-beta.0 --- lerna.json | 2 +- packages/webpack-plugin/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lerna.json b/lerna.json index f0e653671f..4d239b7135 100644 --- a/lerna.json +++ b/lerna.json @@ -2,5 +2,5 @@ "packages": [ "packages/*" ], - "version": "2.8.39" + "version": "2.8.40-beta.0" } diff --git a/packages/webpack-plugin/package.json b/packages/webpack-plugin/package.json index d3dedf1438..fd67d92a1f 100644 --- a/packages/webpack-plugin/package.json +++ b/packages/webpack-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@mpxjs/webpack-plugin", - "version": "2.8.39", + "version": "2.8.40-beta.0", "description": "mpx compile core", "keywords": [ "mpx" From 049d17e2dcfbd72d821cd4799ac32630b07d3d4e Mon Sep 17 00:00:00 2001 From: xuegan Date: Sun, 13 Aug 2023 18:25:38 +0800 Subject: [PATCH 06/59] =?UTF-8?q?feat:=E8=B0=83=E6=95=B4=E5=B1=80=E9=83=A8?= =?UTF-8?q?=E6=9E=84=E5=BB=BA=E5=85=9C=E5=BA=95=E9=A1=B5=E9=9D=A2=E9=80=BB?= =?UTF-8?q?=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/dependencies/ResolveDependency.js | 22 +++++++++---------- packages/webpack-plugin/lib/index.js | 5 ++++- .../lib/json-compiler/helper.js | 11 +++------- .../webpack-plugin/lib/json-compiler/index.js | 12 ++++++++-- 4 files changed, 27 insertions(+), 23 deletions(-) diff --git a/packages/webpack-plugin/lib/dependencies/ResolveDependency.js b/packages/webpack-plugin/lib/dependencies/ResolveDependency.js index 09cdf1edb3..c3323ab9bf 100644 --- a/packages/webpack-plugin/lib/dependencies/ResolveDependency.js +++ b/packages/webpack-plugin/lib/dependencies/ResolveDependency.js @@ -22,7 +22,7 @@ class ResolveDependency extends NullDependency { } getResolved () { - const { resource, packageName, compilation } = this + const { resource, packageName, compilation, issuerResource } = this if (!compilation) return '' const mpx = compilation.__mpx__ if (!mpx) return '' @@ -32,29 +32,27 @@ class ResolveDependency extends NullDependency { const mainComponentsMap = componentsMap.main const currentStaticResourcesMap = staticResourcesMap[packageName] const mainStaticResourcesMap = staticResourcesMap.main - return pagesMap[resourcePath] || currentComponentsMap[resourcePath] || mainComponentsMap[resourcePath] || currentStaticResourcesMap[resourcePath] || mainStaticResourcesMap[resourcePath] || '' + const resolveResult = pagesMap[resourcePath] || currentComponentsMap[resourcePath] || mainComponentsMap[resourcePath] || currentStaticResourcesMap[resourcePath] || mainStaticResourcesMap[resourcePath] || '' + if (!resolveResult) { + if (!this.isPartialCompileFilteredPage(resourcePath)) { + compilation.errors.push(new Error(`Path ${resource} is not a page/component/static resource, which is resolved from ${issuerResource}!`)) + } + } + return resolveResult } - isPartialCompileFilteredPage (resource) { + isPartialCompileFilteredPage (resourcePath) { const { compilation } = this if (!compilation) return '' const mpx = compilation.__mpx__ const { partialCompileFilteredPagesMap } = mpx - const { resourcePath } = parseRequest(resource) return partialCompileFilteredPagesMap[resourcePath] } // resolved可能会动态变更,需用此更新hash updateHash (hash, context) { this.resolved = this.getResolved() - const { resource, issuerResource, compilation } = this - if (this.resolved) { - hash.update(this.resolved) - } else { - if (!this.isPartialCompileFilteredPage(resource)) { - compilation.errors.push(new Error(`Path ${resource} is not a page/component/static resource, which is resolved from ${issuerResource}!`)) - } - } + hash.update(this.resolved) super.updateHash(hash, context) } diff --git a/packages/webpack-plugin/lib/index.js b/packages/webpack-plugin/lib/index.js index cb8f8e798b..3906aa9fcf 100644 --- a/packages/webpack-plugin/lib/index.js +++ b/packages/webpack-plugin/lib/index.js @@ -396,7 +396,10 @@ class MpxWebpackPlugin { }, (obj, resolverContext, callback) => { if (isResolvingPage(obj) && !matchCondition(obj.path, this.options.partialCompile)) { if (mpx) mpx.partialCompileFilteredPagesMap[obj.path] = true - obj.path = false + const { resourcePath } = parseRequest(obj.path) + obj.path = require.resolve('./json-compiler/default-page.mpx') + const infix = obj.query? '&' : '?' + obj.query += `${infix}resourcePath=${resourcePath}` } callback(null, obj) }) diff --git a/packages/webpack-plugin/lib/json-compiler/helper.js b/packages/webpack-plugin/lib/json-compiler/helper.js index 77f8b597a3..87e245a83b 100644 --- a/packages/webpack-plugin/lib/json-compiler/helper.js +++ b/packages/webpack-plugin/lib/json-compiler/helper.js @@ -103,13 +103,7 @@ module.exports = function createJSONHelper ({ loaderContext, emitWarning, custom page = addQuery(page, { isPage: true }) resolve(context, page, loaderContext, (err, resource) => { if (err) { - if (err === RESOLVE_IGNORED_ERR && tarRoot) { - const defaultPage = require.resolve('./default-page.mpx') + `?resourcePath=${context}/${tarRoot}/pages/index.mpx` - resource = defaultPage - aliasPath = '' - } else { - return callback(err) - } + return callback(err) } const { resourcePath, queryObj: { isFirst } } = parseRequest(resource) const ext = path.extname(resourcePath) @@ -133,7 +127,8 @@ module.exports = function createJSONHelper ({ loaderContext, emitWarning, custom const key = [resourcePath, outputPath, tarRoot].join('|') callback(null, entry, { isFirst, - key + key, + resource }) }) } diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index 3c31fe4d06..7b39cea6f0 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -221,14 +221,22 @@ module.exports = function (content) { const localPages = [] const subPackagesCfg = {} const pageKeySet = new Set() - + const defaultPagePath = require.resolve('./default-page.mpx') const processPages = (pages, context, tarRoot = '', callback) => { if (pages) { async.each(pages, (page, callback) => { - processPage(page, context, tarRoot, (err, entry, { isFirst, key } = {}) => { + let beforePageResource = null + processPage(page, context, tarRoot, (err, entry, { isFirst, key, resource } = {}) => { if (err) return callback(err === RESOLVE_IGNORED_ERR ? null : err) if (pageKeySet.has(key)) return callback() + if (resource.startsWith(defaultPagePath)) { + if (beforePageResource || pages.indexOf(page) !== pages.length) { + return callback() + } + } + beforePageResource = resource pageKeySet.add(key) + if (tarRoot && subPackagesCfg) { subPackagesCfg[tarRoot].pages.push(entry) } else { From 0f83ec6592ffcf9ea9371c4ebd5b902447fc3aa7 Mon Sep 17 00:00:00 2001 From: xuegan Date: Tue, 15 Aug 2023 17:09:15 +0800 Subject: [PATCH 07/59] fix: eslint error --- lerna.json | 2 +- packages/webpack-plugin/lib/index.js | 2 +- packages/webpack-plugin/lib/json-compiler/helper.js | 1 - 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/lerna.json b/lerna.json index 4d239b7135..f0e653671f 100644 --- a/lerna.json +++ b/lerna.json @@ -2,5 +2,5 @@ "packages": [ "packages/*" ], - "version": "2.8.40-beta.0" + "version": "2.8.39" } diff --git a/packages/webpack-plugin/lib/index.js b/packages/webpack-plugin/lib/index.js index 3906aa9fcf..8bde5b769b 100644 --- a/packages/webpack-plugin/lib/index.js +++ b/packages/webpack-plugin/lib/index.js @@ -398,7 +398,7 @@ class MpxWebpackPlugin { if (mpx) mpx.partialCompileFilteredPagesMap[obj.path] = true const { resourcePath } = parseRequest(obj.path) obj.path = require.resolve('./json-compiler/default-page.mpx') - const infix = obj.query? '&' : '?' + const infix = obj.query ? '&' : '?' obj.query += `${infix}resourcePath=${resourcePath}` } callback(null, obj) diff --git a/packages/webpack-plugin/lib/json-compiler/helper.js b/packages/webpack-plugin/lib/json-compiler/helper.js index 87e245a83b..8ecc56ca5d 100644 --- a/packages/webpack-plugin/lib/json-compiler/helper.js +++ b/packages/webpack-plugin/lib/json-compiler/helper.js @@ -6,7 +6,6 @@ const parseRequest = require('../utils/parse-request') const addQuery = require('../utils/add-query') const loaderUtils = require('loader-utils') const resolve = require('../utils/resolve') -const { RESOLVE_IGNORED_ERR } = require('../utils/const') module.exports = function createJSONHelper ({ loaderContext, emitWarning, customGetDynamicEntry }) { const mpx = loaderContext.getMpx() From 4a3dfbe1b04f7562d2f0abca689138c653a5e08f Mon Sep 17 00:00:00 2001 From: xuegan Date: Thu, 17 Aug 2023 13:11:30 +0800 Subject: [PATCH 08/59] =?UTF-8?q?fix:=E4=BF=AE=E5=A4=8D=E9=83=A8=E5=88=86?= =?UTF-8?q?=E5=B1=80=E9=83=A8=E6=9E=84=E5=BB=BA=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/dependencies/ResolveDependency.js | 13 ++------- packages/webpack-plugin/lib/index.js | 15 +++++----- .../webpack-plugin/lib/json-compiler/index.js | 29 +++++++++++++------ 3 files changed, 31 insertions(+), 26 deletions(-) diff --git a/packages/webpack-plugin/lib/dependencies/ResolveDependency.js b/packages/webpack-plugin/lib/dependencies/ResolveDependency.js index c3323ab9bf..d3584245ba 100644 --- a/packages/webpack-plugin/lib/dependencies/ResolveDependency.js +++ b/packages/webpack-plugin/lib/dependencies/ResolveDependency.js @@ -1,6 +1,7 @@ const NullDependency = require('webpack/lib/dependencies/NullDependency') const parseRequest = require('../utils/parse-request') const makeSerializable = require('webpack/lib/util/makeSerializable') +const { matchCondition } = require('../utils/match-condition') class ResolveDependency extends NullDependency { constructor (resource, packageName, issuerResource, range) { @@ -26,7 +27,7 @@ class ResolveDependency extends NullDependency { if (!compilation) return '' const mpx = compilation.__mpx__ if (!mpx) return '' - const { pagesMap, componentsMap, staticResourcesMap } = mpx + const { pagesMap, componentsMap, staticResourcesMap, partialCompile } = mpx const { resourcePath } = parseRequest(resource) const currentComponentsMap = componentsMap[packageName] const mainComponentsMap = componentsMap.main @@ -34,21 +35,13 @@ class ResolveDependency extends NullDependency { const mainStaticResourcesMap = staticResourcesMap.main const resolveResult = pagesMap[resourcePath] || currentComponentsMap[resourcePath] || mainComponentsMap[resourcePath] || currentStaticResourcesMap[resourcePath] || mainStaticResourcesMap[resourcePath] || '' if (!resolveResult) { - if (!this.isPartialCompileFilteredPage(resourcePath)) { + if (matchCondition(resourcePath, partialCompile)) { compilation.errors.push(new Error(`Path ${resource} is not a page/component/static resource, which is resolved from ${issuerResource}!`)) } } return resolveResult } - isPartialCompileFilteredPage (resourcePath) { - const { compilation } = this - if (!compilation) return '' - const mpx = compilation.__mpx__ - const { partialCompileFilteredPagesMap } = mpx - return partialCompileFilteredPagesMap[resourcePath] - } - // resolved可能会动态变更,需用此更新hash updateHash (hash, context) { this.resolved = this.getResolved() diff --git a/packages/webpack-plugin/lib/index.js b/packages/webpack-plugin/lib/index.js index 8bde5b769b..6b0ccde8f4 100644 --- a/packages/webpack-plugin/lib/index.js +++ b/packages/webpack-plugin/lib/index.js @@ -383,8 +383,8 @@ class MpxWebpackPlugin { if (this.options.partialCompile) { function isResolvingPage (obj) { // valid query should start with '?' - const query = obj.query || '?' - return parseQuery(query).isPage + const query = parseQuery(obj.query || '?') + return query.isPage && !query.type } // new PartialCompilePlugin(this.options.partialCompile).apply(compiler) compiler.resolverFactory.hooks.resolver.intercept({ @@ -394,12 +394,13 @@ class MpxWebpackPlugin { name: 'MpxPartialCompilePlugin', stage: -100 }, (obj, resolverContext, callback) => { + if (obj.path.startsWith(require.resolve('./json-compiler/default-page.mpx'))) { + return callback(null, obj) + } if (isResolvingPage(obj) && !matchCondition(obj.path, this.options.partialCompile)) { - if (mpx) mpx.partialCompileFilteredPagesMap[obj.path] = true - const { resourcePath } = parseRequest(obj.path) - obj.path = require.resolve('./json-compiler/default-page.mpx') const infix = obj.query ? '&' : '?' - obj.query += `${infix}resourcePath=${resourcePath}` + obj.query += `${infix}resourcePath=${obj.path}` + obj.path = require.resolve('./json-compiler/default-page.mpx') } callback(null, obj) }) @@ -620,7 +621,7 @@ class MpxWebpackPlugin { removedChunks: [], forceProxyEventRules: this.options.forceProxyEventRules, enableRequireAsync: this.options.mode === 'wx' || (this.options.mode === 'ali' && this.options.enableAliRequireAsync), - partialCompileFilteredPagesMap: {}, + partialCompile: this.options.partialCompile, 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 7b39cea6f0..96428777a0 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -224,17 +224,15 @@ module.exports = function (content) { const defaultPagePath = require.resolve('./default-page.mpx') const processPages = (pages, context, tarRoot = '', callback) => { if (pages) { + const pagesCache = [] async.each(pages, (page, callback) => { - let beforePageResource = null processPage(page, context, tarRoot, (err, entry, { isFirst, key, resource } = {}) => { if (err) return callback(err === RESOLVE_IGNORED_ERR ? null : err) if (pageKeySet.has(key)) return callback() if (resource.startsWith(defaultPagePath)) { - if (beforePageResource || pages.indexOf(page) !== pages.length) { - return callback() - } + pagesCache.push(entry) + return callback() } - beforePageResource = resource pageKeySet.add(key) if (tarRoot && subPackagesCfg) { @@ -249,7 +247,18 @@ module.exports = function (content) { } callback() }) - }, callback) + }, () => { + if (tarRoot && subPackagesCfg) { + if (!subPackagesCfg[tarRoot].pages.length) { + subPackagesCfg[tarRoot].pages.push(pagesCache[0]) + } + } else { + if (!localPages.length) { + localPages.push(pagesCache[0]) + } + } + callback() + }) } else { callback() } @@ -585,10 +594,12 @@ module.exports = function (content) { for (const root in subPackagesCfg) { const subPackageCfg = subPackagesCfg[root] // 分包不存在 pages,输出 subPackages 字段会报错 - if (!json.subPackages) { - json.subPackages = [] + if (subPackageCfg.pages.length) { + if (!json.subPackages) { + json.subPackages = [] + } + json.subPackages.push(subPackageCfg) } - json.subPackages.push(subPackageCfg) } const processOutput = (output) => { output = processDynamicEntry(output) From 69be54b89fc2a6c2d66c9547a9472e59189f32bf Mon Sep 17 00:00:00 2001 From: xuegan Date: Thu, 17 Aug 2023 18:59:14 +0800 Subject: [PATCH 09/59] =?UTF-8?q?fix:=E8=A1=A5=E5=85=85=E9=83=A8=E5=88=86?= =?UTF-8?q?=E8=BE=B9=E7=95=8C=E6=83=85=E5=86=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/webpack-plugin/lib/dependencies/ResolveDependency.js | 2 +- packages/webpack-plugin/lib/json-compiler/index.js | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/webpack-plugin/lib/dependencies/ResolveDependency.js b/packages/webpack-plugin/lib/dependencies/ResolveDependency.js index d3584245ba..b56cb636fc 100644 --- a/packages/webpack-plugin/lib/dependencies/ResolveDependency.js +++ b/packages/webpack-plugin/lib/dependencies/ResolveDependency.js @@ -35,7 +35,7 @@ class ResolveDependency extends NullDependency { const mainStaticResourcesMap = staticResourcesMap.main const resolveResult = pagesMap[resourcePath] || currentComponentsMap[resourcePath] || mainComponentsMap[resourcePath] || currentStaticResourcesMap[resourcePath] || mainStaticResourcesMap[resourcePath] || '' if (!resolveResult) { - if (matchCondition(resourcePath, partialCompile)) { + if (!partialCompile || matchCondition(resourcePath, partialCompile)) { compilation.errors.push(new Error(`Path ${resource} is not a page/component/static resource, which is resolved from ${issuerResource}!`)) } } diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index 96428777a0..2097568bde 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -250,11 +250,11 @@ module.exports = function (content) { }, () => { if (tarRoot && subPackagesCfg) { if (!subPackagesCfg[tarRoot].pages.length) { - subPackagesCfg[tarRoot].pages.push(pagesCache[0]) + pagesCache[0] && subPackagesCfg[tarRoot].pages.push(pagesCache[0]) } } else { if (!localPages.length) { - localPages.push(pagesCache[0]) + pagesCache[0] && localPages.push(pagesCache[0]) } } callback() From 1510e1b82fcb7f7b60eb8c50b7fa3f6b3df54db0 Mon Sep 17 00:00:00 2001 From: xuegan Date: Fri, 18 Aug 2023 13:59:38 +0800 Subject: [PATCH 10/59] =?UTF-8?q?fix:=E8=B0=83=E6=95=B4pagesCache=E8=AF=AD?= =?UTF-8?q?=E5=8F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/webpack-plugin/lib/json-compiler/index.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index 2097568bde..46df19d9b4 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -249,12 +249,12 @@ module.exports = function (content) { }) }, () => { if (tarRoot && subPackagesCfg) { - if (!subPackagesCfg[tarRoot].pages.length) { - pagesCache[0] && subPackagesCfg[tarRoot].pages.push(pagesCache[0]) + if (!subPackagesCfg[tarRoot].pages.length && pagesCache[0]) { + subPackagesCfg[tarRoot].pages.push(pagesCache[0]) } } else { - if (!localPages.length) { - pagesCache[0] && localPages.push(pagesCache[0]) + if (!localPages.length && pagesCache[0]) { + localPages.push(pagesCache[0]) } } callback() From f3bfd9bf76756bebe92204e4b87b182b1b5b5502 Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Fri, 18 Aug 2023 17:28:17 +0800 Subject: [PATCH 11/59] v2.8.41 --- lerna.json | 2 +- packages/webpack-plugin/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lerna.json b/lerna.json index 39b022c18f..d99be26bef 100644 --- a/lerna.json +++ b/lerna.json @@ -2,5 +2,5 @@ "packages": [ "packages/*" ], - "version": "2.8.40" + "version": "2.8.41" } diff --git a/packages/webpack-plugin/package.json b/packages/webpack-plugin/package.json index 0e8c160b26..7d1d105f07 100644 --- a/packages/webpack-plugin/package.json +++ b/packages/webpack-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@mpxjs/webpack-plugin", - "version": "2.8.40", + "version": "2.8.41", "description": "mpx compile core", "keywords": [ "mpx" From 4cfa4850ee14eed053e3c2a8f3414a95099c4068 Mon Sep 17 00:00:00 2001 From: xuegan Date: Sun, 20 Aug 2023 20:54:29 +0800 Subject: [PATCH 12/59] =?UTF-8?q?feat:=E5=BC=80=E5=90=AFasyncComponentconf?= =?UTF-8?q?ig=E9=85=8D=E7=BD=AE=E6=97=B6=E8=BE=93=E5=87=BA=E7=BB=84?= =?UTF-8?q?=E4=BB=B6=E8=87=B3=E5=AF=B9=E5=BA=94=E5=88=86=E5=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/webpack-plugin/lib/index.js | 16 ++++++++++++++-- .../webpack-plugin/lib/json-compiler/helper.js | 2 +- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/packages/webpack-plugin/lib/index.js b/packages/webpack-plugin/lib/index.js index 6b0ccde8f4..2f199ec3ad 100644 --- a/packages/webpack-plugin/lib/index.js +++ b/packages/webpack-plugin/lib/index.js @@ -167,6 +167,7 @@ class MpxWebpackPlugin { }, options.nativeConfig) options.webConfig = options.webConfig || {} options.partialCompile = options.mode !== 'web' && options.partialCompile + options.asyncComponentsConfig = options.asyncComponentsConfig || null options.retryRequireAsync = options.retryRequireAsync || false options.enableAliRequireAsync = options.enableAliRequireAsync || false this.options = options @@ -380,12 +381,16 @@ class MpxWebpackPlugin { let mpx - if (this.options.partialCompile) { + if (this.options.partialCompile || this.options.asyncComponentsConfig) { function isResolvingPage (obj) { // valid query should start with '?' const query = parseQuery(obj.query || '?') return query.isPage && !query.type } + function isResolvingComponent (obj) { + const query = parseQuery(obj.query || '?') + return query.isComponent && !query.type + } // new PartialCompilePlugin(this.options.partialCompile).apply(compiler) compiler.resolverFactory.hooks.resolver.intercept({ factory: (type, hook) => { @@ -397,11 +402,18 @@ class MpxWebpackPlugin { if (obj.path.startsWith(require.resolve('./json-compiler/default-page.mpx'))) { return callback(null, obj) } + const infix = obj.query ? '&' : '?' if (isResolvingPage(obj) && !matchCondition(obj.path, this.options.partialCompile)) { - const infix = obj.query ? '&' : '?' obj.query += `${infix}resourcePath=${obj.path}` obj.path = require.resolve('./json-compiler/default-page.mpx') } + if (isResolvingComponent(obj)) { + this.options.asyncComponentsConfig.forEach(item => { + if (matchCondition(obj.path, item)) { + obj.query += `${infix}root=${item.root}&placholder=${item.placeholder}` + } + }) + } callback(null, obj) }) }) diff --git a/packages/webpack-plugin/lib/json-compiler/helper.js b/packages/webpack-plugin/lib/json-compiler/helper.js index 8ecc56ca5d..1e03b0e41f 100644 --- a/packages/webpack-plugin/lib/json-compiler/helper.js +++ b/packages/webpack-plugin/lib/json-compiler/helper.js @@ -45,7 +45,7 @@ module.exports = function createJSONHelper ({ loaderContext, emitWarning, custom if (resolveMode === 'native') { component = urlToRequest(component) } - + component = addQuery(component, { isComponent: true }) resolve(context, component, loaderContext, (err, resource, info) => { if (err) return callback(err) const { resourcePath, queryObj } = parseRequest(resource) From 1ece2b544726e903d993935a6711583b279051ba Mon Sep 17 00:00:00 2001 From: xuegan Date: Mon, 21 Aug 2023 00:13:29 +0800 Subject: [PATCH 13/59] =?UTF-8?q?feat:=E5=A2=9E=E5=8A=A0placeholder?= =?UTF-8?q?=E7=9A=84=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/webpack-plugin/lib/index.js | 2 +- packages/webpack-plugin/lib/json-compiler/helper.js | 9 ++++++--- packages/webpack-plugin/lib/json-compiler/index.js | 11 ++++++++++- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/packages/webpack-plugin/lib/index.js b/packages/webpack-plugin/lib/index.js index 2f199ec3ad..3ed2a314be 100644 --- a/packages/webpack-plugin/lib/index.js +++ b/packages/webpack-plugin/lib/index.js @@ -410,7 +410,7 @@ class MpxWebpackPlugin { if (isResolvingComponent(obj)) { this.options.asyncComponentsConfig.forEach(item => { if (matchCondition(obj.path, item)) { - obj.query += `${infix}root=${item.root}&placholder=${item.placeholder}` + obj.query += `${infix}root=${item.root}&placeholder=${item.placeholder}` } }) } diff --git a/packages/webpack-plugin/lib/json-compiler/helper.js b/packages/webpack-plugin/lib/json-compiler/helper.js index 1e03b0e41f..4e10c2287f 100644 --- a/packages/webpack-plugin/lib/json-compiler/helper.js +++ b/packages/webpack-plugin/lib/json-compiler/helper.js @@ -49,12 +49,15 @@ module.exports = function createJSONHelper ({ loaderContext, emitWarning, custom resolve(context, component, loaderContext, (err, resource, info) => { if (err) return callback(err) const { resourcePath, queryObj } = parseRequest(resource) - + let placeholder = null if (queryObj.root) { // 删除root query resource = addQuery(resource, {}, false, ['root']) // 目前只有微信支持分包异步化 - if (enableRequireAsync) tarRoot = queryObj.root + if (enableRequireAsync) { + tarRoot = queryObj.root + queryObj.placeholder? placeholder = queryObj.placeholder: null + } } const parsed = path.parse(resourcePath) const ext = parsed.ext @@ -84,7 +87,7 @@ module.exports = function createJSONHelper ({ loaderContext, emitWarning, custom } const entry = getDynamicEntry(resource, 'component', outputPath, tarRoot, relativePath) - callback(null, entry) + callback(null, entry, placeholder) }) } diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index 46df19d9b4..11982ce6cf 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -201,13 +201,22 @@ module.exports = function (content) { const processComponents = (components, context, callback) => { if (components) { async.eachOf(components, (component, name, callback) => { - processComponent(component, context, { relativePath }, (err, entry) => { + processComponent(component, context, { relativePath }, (err, entry, placeholder) => { if (err === RESOLVE_IGNORED_ERR) { delete components[name] return callback() } if (err) return callback(err) components[name] = entry + if (placeholder) { + if (json.componentPlaceholder) { + (!json.componentPlaceholder[name])? json.componentPlaceholder[name] = placeholder: null + } else { + json.componentPlaceholder = { + [name]: placeholder + } + } + } callback() }) }, callback) From 6c50bc4a0b34683a34cfd711ced4c64b54668044 Mon Sep 17 00:00:00 2001 From: xuegan Date: Mon, 21 Aug 2023 00:16:32 +0800 Subject: [PATCH 14/59] fix:eslint error --- packages/webpack-plugin/lib/json-compiler/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index 11982ce6cf..f186a62c86 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -210,7 +210,7 @@ module.exports = function (content) { components[name] = entry if (placeholder) { if (json.componentPlaceholder) { - (!json.componentPlaceholder[name])? json.componentPlaceholder[name] = placeholder: null + if (!json.componentPlaceholder[name]) json.componentPlaceholder[name] = placeholder } else { json.componentPlaceholder = { [name]: placeholder From 2e7df377d56f6ad832e887a8a6bd6b458f458c8e Mon Sep 17 00:00:00 2001 From: xuegan Date: Mon, 21 Aug 2023 00:22:54 +0800 Subject: [PATCH 15/59] fix elint error --- packages/webpack-plugin/lib/json-compiler/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/webpack-plugin/lib/json-compiler/helper.js b/packages/webpack-plugin/lib/json-compiler/helper.js index 4e10c2287f..008afadbb8 100644 --- a/packages/webpack-plugin/lib/json-compiler/helper.js +++ b/packages/webpack-plugin/lib/json-compiler/helper.js @@ -56,7 +56,7 @@ module.exports = function createJSONHelper ({ loaderContext, emitWarning, custom // 目前只有微信支持分包异步化 if (enableRequireAsync) { tarRoot = queryObj.root - queryObj.placeholder? placeholder = queryObj.placeholder: null + if (queryObj.placeholder) placeholder = queryObj.placeholder } } const parsed = path.parse(resourcePath) From 54958b8ef61da5830b03e6ce429d3b0e6131f52b Mon Sep 17 00:00:00 2001 From: anotherso1a <1181581742@qq.com> Date: Wed, 23 Aug 2023 19:18:42 +0800 Subject: [PATCH 16/59] perf: Improve web style parsing speed --- packages/webpack-plugin/lib/platform/template/wx/index.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/webpack-plugin/lib/platform/template/wx/index.js b/packages/webpack-plugin/lib/platform/template/wx/index.js index ac0ae2cfae..04ed738dc9 100644 --- a/packages/webpack-plugin/lib/platform/template/wx/index.js +++ b/packages/webpack-plugin/lib/platform/template/wx/index.js @@ -194,12 +194,12 @@ module.exports = function getSpec ({ warn, error }) { const parsed = parseMustache(item.value) if (item.name === 'style') { if (parsed.hasBinding || parsed.result.indexOf('rpx') > -1) { - styleBinding.push(parseMustache(item.value).result) + styleBinding.push(parsed.result) } else { styleBinding.push(JSON.stringify(item.value)) } } else if (item.name === 'wx:style') { - styleBinding.push(parseMustache(item.value).result) + styleBinding.push(parsed.result) } }) return { From e76ee5a8c77e88d384ebfa994825309ec9c43c97 Mon Sep 17 00:00:00 2001 From: anotherso1a <1181581742@qq.com> Date: Wed, 23 Aug 2023 19:27:39 +0800 Subject: [PATCH 17/59] improvement(web): improve web style attr's parsing speed --- .../lib/platform/template/wx/index.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/webpack-plugin/lib/platform/template/wx/index.js b/packages/webpack-plugin/lib/platform/template/wx/index.js index 04ed738dc9..900224db31 100644 --- a/packages/webpack-plugin/lib/platform/template/wx/index.js +++ b/packages/webpack-plugin/lib/platform/template/wx/index.js @@ -190,16 +190,16 @@ module.exports = function getSpec ({ warn, error }) { } const styleBinding = [] el.isStyleParsed = true - el.attrsList.forEach((item) => { + // 不过滤的话每一个属性都要 parse + el.attrsList.filter(item => /^(style|wx:style)$/.test(item.name)).forEach((item) => { const parsed = parseMustache(item.value) - if (item.name === 'style') { - if (parsed.hasBinding || parsed.result.indexOf('rpx') > -1) { - styleBinding.push(parsed.result) - } else { - styleBinding.push(JSON.stringify(item.value)) - } - } else if (item.name === 'wx:style') { + if (item.name === 'wx:style') { styleBinding.push(parsed.result) + // item.name === 'style' + } else if (parsed.hasBinding || parsed.result.indexOf('rpx') > -1) { + styleBinding.push(parsed.result) + } else { + styleBinding.push(JSON.stringify(item.value)) } }) return { From 54031b006bdb9612cb4912beb34a93158c10f36a Mon Sep 17 00:00:00 2001 From: anotherso1a <1181581742@qq.com> Date: Thu, 24 Aug 2023 11:28:00 +0800 Subject: [PATCH 18/59] style: fix code --- packages/webpack-plugin/lib/platform/template/wx/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/webpack-plugin/lib/platform/template/wx/index.js b/packages/webpack-plugin/lib/platform/template/wx/index.js index 900224db31..4d5ba8f5a8 100644 --- a/packages/webpack-plugin/lib/platform/template/wx/index.js +++ b/packages/webpack-plugin/lib/platform/template/wx/index.js @@ -191,7 +191,7 @@ module.exports = function getSpec ({ warn, error }) { const styleBinding = [] el.isStyleParsed = true // 不过滤的话每一个属性都要 parse - el.attrsList.filter(item => /^(style|wx:style)$/.test(item.name)).forEach((item) => { + el.attrsList.filter(item => this.test.test(item.name)).forEach((item) => { const parsed = parseMustache(item.value) if (item.name === 'wx:style') { styleBinding.push(parsed.result) From 54b877f36e943c6e84ccb5c1028e35be1b80727c Mon Sep 17 00:00:00 2001 From: xuegan Date: Thu, 24 Aug 2023 13:21:20 +0800 Subject: [PATCH 19/59] =?UTF-8?q?feat:size-report=E6=94=AF=E6=8C=81ignoreS?= =?UTF-8?q?ubpackage=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/size-report/src/SizeReportPlugin.js | 29 ++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/packages/size-report/src/SizeReportPlugin.js b/packages/size-report/src/SizeReportPlugin.js index f8782972da..92c034d903 100644 --- a/packages/size-report/src/SizeReportPlugin.js +++ b/packages/size-report/src/SizeReportPlugin.js @@ -289,6 +289,7 @@ class SizeReportPlugin { const entrySet = getEntrySet(reportGroup.entryModules, reportGroup.ignoreSubEntry) Object.assign(reportGroup, entrySet, { selfSize: 0, + ignoreSelfSize: 0, selfSizeInfo: {}, sharedSize: 0, sharedSizeInfo: {}, @@ -321,6 +322,9 @@ class SizeReportPlugin { }) })) { reportGroup.selfSize += fillInfo.size + if (reportGroup.ignoreSubpackage && reportGroup.ignoreSubpackage.includes(packageName)) { + reportGroup.ignoreSelfSize += fillInfo.size + } return fillSizeInfo(reportGroup.selfSizeInfo, packageName, fillType, fillInfo) } else if (has(noEntryModules, (noEntryModule) => { return reportGroup.noEntryModules.has(noEntryModule) @@ -335,6 +339,9 @@ class SizeReportPlugin { return reportGroup.selfEntryModules.has(entryModule) })) { reportGroup.selfSize += fillInfo.size + if (reportGroup.ignoreSubpackage && reportGroup.ignoreSubpackage.includes(packageName)) { + reportGroup.ignoreSelfSize += fillInfo.size + } return fillSizeInfo(reportGroup.selfSizeInfo, packageName, fillType, fillInfo) } else if (has(entryModules, (entryModule) => { return reportGroup.selfEntryModules.has(entryModule) || reportGroup.sharedEntryModules.has(entryModule) @@ -671,12 +678,30 @@ class SizeReportPlugin { } if (this.options.threshold) { - checkThreshold(this.options.threshold, sizeSummary.totalSize, packagesSizeInfo) + let ignoreSubpackages = [] + let fitlerIgnoreTotalSize = sizeSummary.totalSize + reportGroups.forEach(group => { + if (group.ignoreSubpackage) { + ignoreSubpackages = ignoreSubpackages.concat(group.ignoreSubpackage) + } + }) + ignoreSubpackages = [...new Set(ignoreSubpackages)] + ignoreSubpackages.forEach(ignoreName => { + if (packagesSizeInfo[ignoreName]) { + fitlerIgnoreTotalSize -= packagesSizeInfo[ignoreName] + } + }) + + checkThreshold(this.options.threshold, fitlerIgnoreTotalSize, packagesSizeInfo) } reportGroups.forEach((reportGroup) => { if (reportGroup.threshold) { - checkThreshold(reportGroup.threshold, reportGroup.selfSize, reportGroup.selfSizeInfo, reportGroup.name || 'anonymous group') + let groupSelfSize = reportGroup.selfSize + if (reportGroup.ignoreSelfSize) { + groupSelfSize -= reportGroup.ignoreSelfSize + } + checkThreshold(reportGroup.threshold, groupSelfSize, reportGroup.selfSizeInfo, reportGroup.name || 'anonymous group') } }) From 1844749b1482c837d5960ac75e6ae4454a8428ca Mon Sep 17 00:00:00 2001 From: xuegan Date: Thu, 24 Aug 2023 13:25:19 +0800 Subject: [PATCH 20/59] =?UTF-8?q?feat:=E8=A1=A5=E5=85=85=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/size-report/README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/size-report/README.md b/packages/size-report/README.md index 4c43a15c8e..055b176b87 100644 --- a/packages/size-report/README.md +++ b/packages/size-report/README.md @@ -76,7 +76,9 @@ const MpxSizeReportPlugin = require('@mpxjs/size-report') // 有的时候你可能希望计算纯 js 入口引入的体积(不包含组件和页面),这种情况下需要使用 noEntryModules noEntryModules: { include: 'src/lib/sdk.js' - } + }, + // group 阈值校验时忽略该分包体积,总包体积校验时也会忽略该分包体积 + ignoreSubpackage: ['new-homepage'] } ], // 配置模块引用链路记录规则,符合规则的模块的引用关系会输出在moduleEntryGraph中 From f337f071f355dea7595df0f0ab32849db4413d76 Mon Sep 17 00:00:00 2001 From: anotherso1a <1181581742@qq.com> Date: Thu, 24 Aug 2023 14:47:38 +0800 Subject: [PATCH 21/59] fix: Make the createIntersectionObserver parameter consistent with the mini program --- packages/core/src/vuePlugin.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/src/vuePlugin.js b/packages/core/src/vuePlugin.js index b7862622fe..791c1c635d 100644 --- a/packages/core/src/vuePlugin.js +++ b/packages/core/src/vuePlugin.js @@ -25,7 +25,7 @@ export default function install (Vue) { Vue.prototype.createSelectorQuery = function () { return webApi.createSelectorQuery().in(this) } - Vue.prototype.createIntersectionObserver = function (component, options) { - return webApi.createIntersectionObserver(component, options) + Vue.prototype.createIntersectionObserver = function (options) { + return webApi.createIntersectionObserver(this, options) } } From 7b40b24a86e60c040aa6c63e0e3518f4cbd7b628 Mon Sep 17 00:00:00 2001 From: xuegan Date: Fri, 25 Aug 2023 16:14:26 +0800 Subject: [PATCH 22/59] =?UTF-8?q?feat:=E8=B0=83=E6=95=B4ignoreSubpackages?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E8=87=B3=E5=A4=96=E5=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/size-report/README.md | 8 +++--- packages/size-report/src/SizeReportPlugin.js | 30 +++++++++----------- 2 files changed, 17 insertions(+), 21 deletions(-) diff --git a/packages/size-report/README.md b/packages/size-report/README.md index 055b176b87..5f92bd7c92 100644 --- a/packages/size-report/README.md +++ b/packages/size-report/README.md @@ -43,6 +43,8 @@ const MpxSizeReportPlugin = require('@mpxjs/size-report') port: 0, // 本地服务端口,非必填,默认 0(随机端口) host: '127.0.0.1', // 本地服务host,非必填 }, + // group 阈值校验时忽略该分包体积,总包体积校验时也会忽略该分包体积 + ignoreSubpackages: ['new-homepage'], // 体积报告生成后输出的文件地址名,路径相对为 dist/wx 或者 dist/ali filename: '../report.json', // 配置阈值,此处代表总包体积阈值为 16MB,分包体积阈值为 2MB,超出将会触发编译报错提醒,该报错不阻断构建 @@ -76,9 +78,7 @@ const MpxSizeReportPlugin = require('@mpxjs/size-report') // 有的时候你可能希望计算纯 js 入口引入的体积(不包含组件和页面),这种情况下需要使用 noEntryModules noEntryModules: { include: 'src/lib/sdk.js' - }, - // group 阈值校验时忽略该分包体积,总包体积校验时也会忽略该分包体积 - ignoreSubpackage: ['new-homepage'] + } } ], // 配置模块引用链路记录规则,符合规则的模块的引用关系会输出在moduleEntryGraph中 @@ -86,7 +86,7 @@ const MpxSizeReportPlugin = require('@mpxjs/size-report') include: [ 'src/components/tools.js' ] - } + }, // 是否收集页面维度体积详情,默认 false reportPages: true, // 是否收集资源维度体积详情,默认 false diff --git a/packages/size-report/src/SizeReportPlugin.js b/packages/size-report/src/SizeReportPlugin.js index 92c034d903..a09ec553c9 100644 --- a/packages/size-report/src/SizeReportPlugin.js +++ b/packages/size-report/src/SizeReportPlugin.js @@ -109,6 +109,8 @@ class SizeReportPlugin { const needEntryPathRules = this.options.needEntryPathRules || {} + const ignoreSubpackages = this.options.ignoreSubpackages + if (reportPages) { Object.entries(mpx.pagesMap).forEach(([resourcePath, name]) => { reportGroups.push({ @@ -322,7 +324,7 @@ class SizeReportPlugin { }) })) { reportGroup.selfSize += fillInfo.size - if (reportGroup.ignoreSubpackage && reportGroup.ignoreSubpackage.includes(packageName)) { + if (ignoreSubpackages && ignoreSubpackages.includes(packageName)) { reportGroup.ignoreSelfSize += fillInfo.size } return fillSizeInfo(reportGroup.selfSizeInfo, packageName, fillType, fillInfo) @@ -339,7 +341,7 @@ class SizeReportPlugin { return reportGroup.selfEntryModules.has(entryModule) })) { reportGroup.selfSize += fillInfo.size - if (reportGroup.ignoreSubpackage && reportGroup.ignoreSubpackage.includes(packageName)) { + if (ignoreSubpackages && ignoreSubpackages.includes(packageName)) { reportGroup.ignoreSelfSize += fillInfo.size } return fillSizeInfo(reportGroup.selfSizeInfo, packageName, fillType, fillInfo) @@ -678,21 +680,15 @@ class SizeReportPlugin { } if (this.options.threshold) { - let ignoreSubpackages = [] - let fitlerIgnoreTotalSize = sizeSummary.totalSize - reportGroups.forEach(group => { - if (group.ignoreSubpackage) { - ignoreSubpackages = ignoreSubpackages.concat(group.ignoreSubpackage) - } - }) - ignoreSubpackages = [...new Set(ignoreSubpackages)] - ignoreSubpackages.forEach(ignoreName => { - if (packagesSizeInfo[ignoreName]) { - fitlerIgnoreTotalSize -= packagesSizeInfo[ignoreName] - } - }) - - checkThreshold(this.options.threshold, fitlerIgnoreTotalSize, packagesSizeInfo) + let filterIgnoreTotalSize = sizeSummary.totalSize + if (ignoreSubpackages) { + ignoreSubpackages.forEach(ignoreName => { + if (packagesSizeInfo[ignoreName]) { + filterIgnoreTotalSize -= packagesSizeInfo[ignoreName] + } + }) + } + checkThreshold(this.options.threshold, filterIgnoreTotalSize, packagesSizeInfo) } reportGroups.forEach((reportGroup) => { From 22475aeb3aa8cb4f1e31932114027011dc28c7f9 Mon Sep 17 00:00:00 2001 From: xuegan Date: Fri, 25 Aug 2023 20:14:48 +0800 Subject: [PATCH 23/59] =?UTF-8?q?fix:=E4=BF=AE=E5=A4=8D=E6=96=87=E6=A1=A3p?= =?UTF-8?q?refetch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs-vuepress/.vuepress/config.js | 1 + 1 file changed, 1 insertion(+) diff --git a/docs-vuepress/.vuepress/config.js b/docs-vuepress/.vuepress/config.js index c61955049d..e971a27c39 100644 --- a/docs-vuepress/.vuepress/config.js +++ b/docs-vuepress/.vuepress/config.js @@ -135,6 +135,7 @@ module.exports = { description: '深度性能优化的增强型小程序开发框架' }, }, + shouldPrefetch: () => false, plugins: { '@vuepress/pwa': { serviceWorker: true, From 3ca7bcddb35d9772ce2a5ce6880dda3e4dcdc688 Mon Sep 17 00:00:00 2001 From: xuegan Date: Sun, 27 Aug 2023 00:38:55 +0800 Subject: [PATCH 24/59] =?UTF-8?q?feat:=E4=BF=AE=E5=A4=8D=E5=BC=82=E6=AD=A5?= =?UTF-8?q?=E7=BB=84=E4=BB=B6=E9=85=8D=E7=BD=AE=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/webpack-plugin/lib/index.js | 28 ++++++++++-------- .../lib/json-compiler/helper.js | 13 +++++++-- .../webpack-plugin/lib/json-compiler/index.js | 29 ++++--------------- 3 files changed, 31 insertions(+), 39 deletions(-) diff --git a/packages/webpack-plugin/lib/index.js b/packages/webpack-plugin/lib/index.js index 3ed2a314be..2628103119 100644 --- a/packages/webpack-plugin/lib/index.js +++ b/packages/webpack-plugin/lib/index.js @@ -381,16 +381,12 @@ class MpxWebpackPlugin { let mpx - if (this.options.partialCompile || this.options.asyncComponentsConfig) { + if (this.options.partialCompile) { function isResolvingPage (obj) { // valid query should start with '?' const query = parseQuery(obj.query || '?') return query.isPage && !query.type } - function isResolvingComponent (obj) { - const query = parseQuery(obj.query || '?') - return query.isComponent && !query.type - } // new PartialCompilePlugin(this.options.partialCompile).apply(compiler) compiler.resolverFactory.hooks.resolver.intercept({ factory: (type, hook) => { @@ -407,13 +403,13 @@ class MpxWebpackPlugin { obj.query += `${infix}resourcePath=${obj.path}` obj.path = require.resolve('./json-compiler/default-page.mpx') } - if (isResolvingComponent(obj)) { - this.options.asyncComponentsConfig.forEach(item => { - if (matchCondition(obj.path, item)) { - obj.query += `${infix}root=${item.root}&placeholder=${item.placeholder}` - } - }) - } + // if (isResolvingComponent(obj)) { + // this.options.asyncComponentsConfig.forEach(item => { + // if (matchCondition(obj.path, item)) { + // obj.query += `${infix}root=${item.root}&placeholder=${item.placeholder}` + // } + // }) + // } callback(null, obj) }) }) @@ -634,6 +630,7 @@ class MpxWebpackPlugin { forceProxyEventRules: this.options.forceProxyEventRules, enableRequireAsync: this.options.mode === 'wx' || (this.options.mode === 'ali' && this.options.enableAliRequireAsync), partialCompile: this.options.partialCompile, + asyncComponentsConfig: this.options.asyncComponentsConfig, pathHash: (resourcePath) => { if (this.options.pathHashMode === 'relative' && this.options.projectRoot) { return hash(path.relative(this.options.projectRoot, resourcePath)) @@ -1039,6 +1036,13 @@ class MpxWebpackPlugin { const range = expr.arguments[0].range const context = parser.state.module.context const { queryObj } = parseRequest(request) + if (!queryObj.root && mpx.asyncComponentsConfig) { + mpx.asyncComponentsConfig.forEach(item => { + if (matchCondition(resourcePath, item)) { + queryObj.root = item.root + } + }) + } if (queryObj.root) { // 删除root query request = addQuery(request, {}, false, ['root']) diff --git a/packages/webpack-plugin/lib/json-compiler/helper.js b/packages/webpack-plugin/lib/json-compiler/helper.js index 008afadbb8..1e172c87e2 100644 --- a/packages/webpack-plugin/lib/json-compiler/helper.js +++ b/packages/webpack-plugin/lib/json-compiler/helper.js @@ -6,6 +6,7 @@ const parseRequest = require('../utils/parse-request') const addQuery = require('../utils/add-query') const loaderUtils = require('loader-utils') const resolve = require('../utils/resolve') +const { matchCondition } = require('../utils/match-condition') module.exports = function createJSONHelper ({ loaderContext, emitWarning, customGetDynamicEntry }) { const mpx = loaderContext.getMpx() @@ -17,6 +18,7 @@ module.exports = function createJSONHelper ({ loaderContext, emitWarning, custom const getOutputPath = mpx.getOutputPath const mode = mpx.mode const enableRequireAsync = mpx.enableRequireAsync + const asyncComponentsConfig = mpx.asyncComponentsConfig const isUrlRequest = r => isUrlRequestRaw(r, root, externals) const urlToRequest = r => loaderUtils.urlToRequest(r) @@ -49,14 +51,19 @@ module.exports = function createJSONHelper ({ loaderContext, emitWarning, custom resolve(context, component, loaderContext, (err, resource, info) => { if (err) return callback(err) const { resourcePath, queryObj } = parseRequest(resource) - let placeholder = null + if (!queryObj.root && asyncComponentsConfig) { + asyncComponentsConfig.forEach(item => { + if (matchCondition(resourcePath, item)) { + queryObj.root = item.root + } + }) + } if (queryObj.root) { // 删除root query resource = addQuery(resource, {}, false, ['root']) // 目前只有微信支持分包异步化 if (enableRequireAsync) { tarRoot = queryObj.root - if (queryObj.placeholder) placeholder = queryObj.placeholder } } const parsed = path.parse(resourcePath) @@ -87,7 +94,7 @@ module.exports = function createJSONHelper ({ loaderContext, emitWarning, custom } const entry = getDynamicEntry(resource, 'component', outputPath, tarRoot, relativePath) - callback(null, entry, placeholder) + callback(null, entry, tarRoot) }) } diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index f186a62c86..589b595866 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -142,22 +142,6 @@ module.exports = function (content) { } } - // 校验异步组件占位符 componentPlaceholder 不为空 - if (mpx.enableRequireAsync) { - const { usingComponents, componentPlaceholder = {} } = json - if (usingComponents) { - for (const compName in usingComponents) { - const compPath = usingComponents[compName] - if (!/\?root=/g.test(compPath)) continue - const compPlaceholder = componentPlaceholder[compName] - if (!compPlaceholder) { - const errMsg = `componentPlaceholder of "${compName}" doesn't exist! \n\r` - emitError(errMsg) - } - } - } - } - // 快应用补全json配置,必填项 if (mode === 'qa' && isApp) { const defaultConf = { @@ -201,20 +185,17 @@ module.exports = function (content) { const processComponents = (components, context, callback) => { if (components) { async.eachOf(components, (component, name, callback) => { - processComponent(component, context, { relativePath }, (err, entry, placeholder) => { + processComponent(component, context, { relativePath }, (err, entry, root) => { if (err === RESOLVE_IGNORED_ERR) { delete components[name] return callback() } if (err) return callback(err) components[name] = entry - if (placeholder) { - if (json.componentPlaceholder) { - if (!json.componentPlaceholder[name]) json.componentPlaceholder[name] = placeholder - } else { - json.componentPlaceholder = { - [name]: placeholder - } + if (root) { + if (!json.componentPlaceholder || !json.componentPlaceholder[name]) { + const errMsg = `componentPlaceholder of "${name}" doesn't exist! \n\r` + emitError(errMsg) } } callback() From 263a1cb132f8509d6854de52eb5e57d0d0e61ee2 Mon Sep 17 00:00:00 2001 From: xuegan Date: Sun, 27 Aug 2023 00:43:42 +0800 Subject: [PATCH 25/59] fix:eslint error --- packages/webpack-plugin/lib/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/webpack-plugin/lib/index.js b/packages/webpack-plugin/lib/index.js index 2628103119..23d644b051 100644 --- a/packages/webpack-plugin/lib/index.js +++ b/packages/webpack-plugin/lib/index.js @@ -1035,7 +1035,7 @@ class MpxWebpackPlugin { let request = expr.arguments[0].value const range = expr.arguments[0].range const context = parser.state.module.context - const { queryObj } = parseRequest(request) + const { queryObj, resourcePath } = parseRequest(request) if (!queryObj.root && mpx.asyncComponentsConfig) { mpx.asyncComponentsConfig.forEach(item => { if (matchCondition(resourcePath, item)) { From b8deb2e6e82f0edd66b6a78a93731e357b8f1e55 Mon Sep 17 00:00:00 2001 From: xuegan Date: Sun, 27 Aug 2023 15:21:07 +0800 Subject: [PATCH 26/59] =?UTF-8?q?feat:=E8=A1=A5=E5=85=85=E6=89=B9=E9=87=8F?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E5=BC=82=E6=AD=A5=E5=88=86=E5=8C=85=E6=96=87?= =?UTF-8?q?=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs-vuepress/api/compile.md | 53 ++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/docs-vuepress/api/compile.md b/docs-vuepress/api/compile.md index 794548da1c..04252a0188 100644 --- a/docs-vuepress/api/compile.md +++ b/docs-vuepress/api/compile.md @@ -250,6 +250,7 @@ module.exports = defineConfig({ }) ``` ::: + ### externalClasses - **类型**:`Array` @@ -488,6 +489,7 @@ module.exports = defineConfig({ }) ``` ::: + ### autoSplit - **类型**:`boolean` @@ -1126,8 +1128,6 @@ module.exports = defineConfig({ ``` ::: - - ### i18n ```js @@ -1404,6 +1404,55 @@ module.exports = defineConfig({ 该特性只能用于**开发环境**,默认情况下会阻止所有页面(**入口 app.mpx 除外**)的打包。 ::: +### asyncComponentsConfig + +- **类型**:`Array【{ include: string | RegExp | Function | Array, root: string }】` + * include: 同 webpack include 规则 + * root: 匹配规则的组件或js模块的输出分包名 + +- **详细**:异步分包场景下批量设置组件或 js 模块的异步分包,提升资源异步分包输出的灵活性。 + +- **示例**: + +```js +// include 可以是正则、字符串、函数、数组 +new MpxWebpackPlugin({ + asyncComponentsConfig: [ + { + include: '/project/pages', // 文件路径包含 '/project/pages' 的组件或者 require.async 异步引用的js 模块都会被打包至sub1分包 + root: 'sub1' + } + ] +}) +``` + +::: tip @mpxjs/cli@3.x 版本配置如下 +```js +// vue.config.js +module.exports = defineConfig({ + pluginOptions: { + mpx: { + plugin: { + // include 可以是正则、字符串、函数、数组 + partialCompile: [ + { + include: '/project/pages', // 文件路径包含 '/project/pages' 的组件或者 require.async 异步引用的js 模块都会被打包至sub1分包 + root: 'sub1' + } + ] + } + } + } +}) +``` +::: + +:::warning +* 该配置匹配的组件,若使用方在引用路径已设置?root,则以引用路径中的?root为最高优先级 +* 本功能默认不会增加componentPlaceholder配置,开启异步分包的组件开发者务必配置componentPlaceholder +* 本功能只会对使用require.async异步引用的js模块生效,若引用路径中已配置?root,则以路径中?root优先 +::: + ## MpxWebpackPlugin static methods `MpxWebpackPlugin` 通过静态方法暴露了以下五个内置 loader,详情如下: From e8cad9e1b6b1506ac889da05ad22e43ef2f4b849 Mon Sep 17 00:00:00 2001 From: hiyuki <67888883329@qq.com> Date: Wed, 30 Aug 2023 19:30:17 +0800 Subject: [PATCH 27/59] fix ali globalComponents --- .../webpack-plugin/lib/json-compiler/index.js | 18 ++++--- packages/webpack-plugin/lib/loader.js | 11 +---- packages/webpack-plugin/lib/native-loader.js | 15 ++---- .../lib/platform/json/wx/index.js | 49 +++++++++++++------ .../wx/component-config/hypen-tag-name.js | 8 +-- .../template/wx/component-config/index.js | 4 +- 6 files changed, 57 insertions(+), 48 deletions(-) diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index 46df19d9b4..af4b03e795 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -14,6 +14,7 @@ const RecordGlobalComponentsDependency = require('../dependencies/RecordGlobalCo const RecordIndependentDependency = require('../dependencies/RecordIndependentDependency') const { MPX_DISABLE_EXTRACTOR_CACHE, RESOLVE_IGNORED_ERR, JSON_JS_EXT } = require('../utils/const') const resolve = require('../utils/resolve') +const isEmptyObject = require('../utils/is-empty-object') module.exports = function (content) { const nativeCallback = this.async() @@ -177,14 +178,14 @@ module.exports = function (content) { type: 'json', waterfall: true, warn: emitWarning, - error: emitError + error: emitError, + data: { + // polyfill global usingComponents & record globalComponents + globalComponents: mpx.usingComponents + } } if (!isApp) { rulesRunnerOptions.mainKey = pagesMap[resourcePath] ? 'page' : 'component' - // polyfill global usingComponents - rulesRunnerOptions.data = { - globalComponents: mpx.usingComponents - } } const rulesRunner = getRulesRunner(rulesRunnerOptions) @@ -193,9 +194,12 @@ module.exports = function (content) { rulesRunner(json) } - if (isApp && json.usingComponents) { + if (isApp) { + Object.assign(mpx.usingComponents, json.usingComponents) // 在 rulesRunner 运行后保存全局注册组件 - this._module.addPresentationalDependency(new RecordGlobalComponentsDependency(json.usingComponents, this.context)) + // todo 其余地方在使用mpx.usingComponents时存在缓存问题,要规避该问题需要在所有使用mpx.usingComponents的loader中添加app resourcePath作为fileDependency,但对于缓存有效率影响巨大 + // todo 需要考虑一种精准控制缓存的方式,仅在全局组件发生变更时才使相关使用方的缓存失效,例如按需在相关模块上动态添加request query? + this._module.addPresentationalDependency(new RecordGlobalComponentsDependency(mpx.usingComponents, this.context)) } const processComponents = (components, context, callback) => { diff --git a/packages/webpack-plugin/lib/loader.js b/packages/webpack-plugin/lib/loader.js index 7b5312fd94..9061f21083 100644 --- a/packages/webpack-plugin/lib/loader.js +++ b/packages/webpack-plugin/lib/loader.js @@ -120,7 +120,6 @@ module.exports = function (content) { let usingComponents = [].concat(Object.keys(mpx.usingComponents)) let componentPlaceholder = [] - let componentGenerics = {} if (parts.json && parts.json.content) { @@ -134,18 +133,12 @@ module.exports = function (content) { } if (!isApp) { rulesRunnerOptions.mainKey = pagesMap[resourcePath] ? 'page' : 'component' - // polyfill global usingComponents - // 预读json时无需注入polyfill全局组件 - // rulesRunnerOptions.data = { - // globalComponents: mpx.usingComponents - // } } - + const rulesRunner = getRulesRunner(rulesRunnerOptions) try { const ret = JSON5.parse(parts.json.content) + if (rulesRunner) rulesRunner(ret) if (ret.usingComponents) { - const rulesRunner = getRulesRunner(rulesRunnerOptions) - if (rulesRunner) rulesRunner(ret) usingComponents = usingComponents.concat(Object.keys(ret.usingComponents)) } if (ret.componentPlaceholder) { diff --git a/packages/webpack-plugin/lib/native-loader.js b/packages/webpack-plugin/lib/native-loader.js index 64c81893a6..a1d61f23f0 100644 --- a/packages/webpack-plugin/lib/native-loader.js +++ b/packages/webpack-plugin/lib/native-loader.js @@ -54,7 +54,7 @@ module.exports = function (content) { this.resolve(parsed.dir, resourceName + extName, callback) } - function checkCSSLangFiles (callback) { + function checkCSSLangFiles(callback) { const langs = mpx.nativeConfig.cssLangs || ['less', 'stylus', 'scss', 'sass'] const results = [] async.eachOf(langs, function (lang, i, callback) { @@ -79,7 +79,7 @@ module.exports = function (content) { }) } - function checkJSONJSFile (callback) { + function checkJSONJSFile(callback) { checkFileExists(JSON_JS_EXT, (err, result) => { if (!err && result) { typeResourceMap.json = result @@ -137,6 +137,7 @@ module.exports = function (content) { } catch (e) { return callback(e) } + let usingComponents = Object.keys(mpx.usingComponents) const rulesRunnerOptions = { mode, srcMode, @@ -147,16 +148,10 @@ module.exports = function (content) { } if (!isApp) { rulesRunnerOptions.mainKey = pagesMap[resourcePath] ? 'page' : 'component' - // polyfill global usingComponents - // 预读json时无需注入polyfill全局组件 - // rulesRunnerOptions.data = { - // globalComponents: mpx.usingComponents - // } } - let usingComponents = Object.keys(mpx.usingComponents) + const rulesRunner = getRulesRunner(rulesRunnerOptions) + if (rulesRunner) rulesRunner(json) if (json.usingComponents) { - const rulesRunner = getRulesRunner(rulesRunnerOptions) - if (rulesRunner) rulesRunner(json) usingComponents = usingComponents.concat(Object.keys(json.usingComponents)) } const { diff --git a/packages/webpack-plugin/lib/platform/json/wx/index.js b/packages/webpack-plugin/lib/platform/json/wx/index.js index f0ec54bd1b..cbc631a582 100644 --- a/packages/webpack-plugin/lib/platform/json/wx/index.js +++ b/packages/webpack-plugin/lib/platform/json/wx/index.js @@ -7,13 +7,13 @@ const { capitalToHyphen } = require('../../../utils/string') const mpxViewPath = normalize.lib('runtime/components/ali/mpx-view.mpx') const mpxTextPath = normalize.lib('runtime/components/ali/mpx-text.mpx') -module.exports = function getSpec ({ warn, error }) { - function print (mode, path, isError) { +module.exports = function getSpec({ warn, error }) { + function print(mode, path, isError) { const msg = `Json path <${path}> is not supported in ${mode} environment!` isError ? error(msg) : warn(msg) } - function deletePath (opts) { + function deletePath(opts) { let isError = opts let shouldLog = true if (typeof opts === 'object') { @@ -37,7 +37,7 @@ module.exports = function getSpec ({ warn, error }) { * @desc 在app.mpx里配置usingComponents作为全局组件 */ - function addGlobalComponents (input, { globalComponents }) { + function addGlobalComponents(input, { globalComponents }) { if (globalComponents) { input.usingComponents = Object.assign({}, globalComponents, input.usingComponents) } @@ -45,7 +45,7 @@ module.exports = function getSpec ({ warn, error }) { } // 处理支付宝 componentPlaceholder 不支持 view、text 原生标签 - function aliComponentPlaceholderFallback (input) { + function aliComponentPlaceholderFallback(input) { // 处理 驼峰转连字符 input = componentNameCapitalToHyphen('componentPlaceholder')(input) const componentPlaceholder = input.componentPlaceholder @@ -70,8 +70,15 @@ module.exports = function getSpec ({ warn, error }) { return input } + function fillGlobalComponents(input, { globalComponents }) { + if (globalComponents) { + Object.assign(globalComponents, input.usingComponents) + } + return input + } + // 处理 ali swan 的组件名大写字母转连字符:WordExample/wordExample -> word-example - function componentNameCapitalToHyphen (type) { + function componentNameCapitalToHyphen(type) { return function (input) { // 百度和支付宝不支持大写组件标签名,统一转成带“-”和小写的形式。百度自带标签不会有带大写的情况 // 后续可能需要考虑这些平台支持 componentGenerics 后的转换 https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/generics.html @@ -135,13 +142,13 @@ module.exports = function getSpec ({ warn, error }) { const windowRules = [ { test: 'navigationBarTitleText', - ali (input) { + ali(input) { return changeKey(input, this.test, 'defaultTitle') } }, { test: 'enablePullDownRefresh', - ali (input) { + ali(input) { input = changeKey(input, this.test, 'pullRefresh') if (input.pullRefresh) { input.allowsBounceVertical = 'YES' @@ -152,7 +159,7 @@ module.exports = function getSpec ({ warn, error }) { }, { test: 'navigationBarBackgroundColor', - ali (input) { + ali(input) { return changeKey(input, this.test, 'titleBarColor') } }, @@ -229,19 +236,19 @@ module.exports = function getSpec ({ warn, error }) { list: [ { test: 'text', - ali (input) { + ali(input) { return changeKey(input, this.test, 'name') } }, { test: 'iconPath', - ali (input) { + ali(input) { return changeKey(input, this.test, 'icon') } }, { test: 'selectedIconPath', - ali (input) { + ali(input) { return changeKey(input, this.test, 'activeIcon') } } @@ -249,13 +256,13 @@ module.exports = function getSpec ({ warn, error }) { rules: [ { test: 'color', - ali (input) { + ali(input) { return changeKey(input, this.test, 'textColor') } }, { test: 'list', - ali (input) { + ali(input) { const value = input.list delete input.list input.items = value.map(item => { @@ -318,6 +325,20 @@ module.exports = function getSpec ({ warn, error }) { tt: deletePath(), jd: deletePath(true) }, + { + test: 'usingComponents', + ali: componentNameCapitalToHyphen('usingComponents'), + swan: componentNameCapitalToHyphen('usingComponents') + }, + { + test: 'usingComponents', + // todo ali 2.0已支持全局组件,待移除 + ali: fillGlobalComponents, + qq: fillGlobalComponents, + swan: fillGlobalComponents, + tt: fillGlobalComponents, + jd: fillGlobalComponents + }, { test: 'usingComponents', // todo ali 2.0已支持全局组件,待移除 diff --git a/packages/webpack-plugin/lib/platform/template/wx/component-config/hypen-tag-name.js b/packages/webpack-plugin/lib/platform/template/wx/component-config/hypen-tag-name.js index 61c3f701cb..a6f7dace79 100644 --- a/packages/webpack-plugin/lib/platform/template/wx/component-config/hypen-tag-name.js +++ b/packages/webpack-plugin/lib/platform/template/wx/component-config/hypen-tag-name.js @@ -1,14 +1,10 @@ const { capitalToHyphen } = require('../../../../utils/string') module.exports = function () { - function convertTagName (name) { - return capitalToHyphen(name) - } - return { // tag name contains capital letters test: /[A-Z]/, - ali: convertTagName, - swan: convertTagName + ali: capitalToHyphen, + swan: capitalToHyphen } } diff --git a/packages/webpack-plugin/lib/platform/template/wx/component-config/index.js b/packages/webpack-plugin/lib/platform/template/wx/component-config/index.js index 5121a16e60..c19ceb4d1a 100644 --- a/packages/webpack-plugin/lib/platform/template/wx/component-config/index.js +++ b/packages/webpack-plugin/lib/platform/template/wx/component-config/index.js @@ -8,7 +8,7 @@ const checkbox = require('./checkbox') const coverImage = require('./cover-image') const coverView = require('./cover-view') const form = require('./form') -const HyphenTagName = require('./hypen-tag-name') +const hyphenTagName = require('./hypen-tag-name') const icon = require('./icon') const image = require('./image') const input = require('./input') @@ -118,7 +118,7 @@ module.exports = function getComponentConfigs ({ warn, error }) { camera({ print }), livePlayer({ print }), livePusher({ print }), - HyphenTagName({ print }), + hyphenTagName({ print }), component() ] } From 17609fc54a5b0710216f20afe06dd2534c5489ff Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Thu, 31 Aug 2023 14:09:55 +0800 Subject: [PATCH 28/59] fix lint --- .../webpack-plugin/lib/json-compiler/index.js | 1 - packages/webpack-plugin/lib/native-loader.js | 4 +-- .../lib/platform/json/wx/index.js | 30 +++++++++---------- 3 files changed, 17 insertions(+), 18 deletions(-) diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index af4b03e795..c284c9f97c 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -14,7 +14,6 @@ const RecordGlobalComponentsDependency = require('../dependencies/RecordGlobalCo const RecordIndependentDependency = require('../dependencies/RecordIndependentDependency') const { MPX_DISABLE_EXTRACTOR_CACHE, RESOLVE_IGNORED_ERR, JSON_JS_EXT } = require('../utils/const') const resolve = require('../utils/resolve') -const isEmptyObject = require('../utils/is-empty-object') module.exports = function (content) { const nativeCallback = this.async() diff --git a/packages/webpack-plugin/lib/native-loader.js b/packages/webpack-plugin/lib/native-loader.js index a1d61f23f0..e025cc428f 100644 --- a/packages/webpack-plugin/lib/native-loader.js +++ b/packages/webpack-plugin/lib/native-loader.js @@ -54,7 +54,7 @@ module.exports = function (content) { this.resolve(parsed.dir, resourceName + extName, callback) } - function checkCSSLangFiles(callback) { + function checkCSSLangFiles (callback) { const langs = mpx.nativeConfig.cssLangs || ['less', 'stylus', 'scss', 'sass'] const results = [] async.eachOf(langs, function (lang, i, callback) { @@ -79,7 +79,7 @@ module.exports = function (content) { }) } - function checkJSONJSFile(callback) { + function checkJSONJSFile (callback) { checkFileExists(JSON_JS_EXT, (err, result) => { if (!err && result) { typeResourceMap.json = result diff --git a/packages/webpack-plugin/lib/platform/json/wx/index.js b/packages/webpack-plugin/lib/platform/json/wx/index.js index cbc631a582..182e96a421 100644 --- a/packages/webpack-plugin/lib/platform/json/wx/index.js +++ b/packages/webpack-plugin/lib/platform/json/wx/index.js @@ -7,13 +7,13 @@ const { capitalToHyphen } = require('../../../utils/string') const mpxViewPath = normalize.lib('runtime/components/ali/mpx-view.mpx') const mpxTextPath = normalize.lib('runtime/components/ali/mpx-text.mpx') -module.exports = function getSpec({ warn, error }) { - function print(mode, path, isError) { +module.exports = function getSpec ({ warn, error }) { + function print (mode, path, isError) { const msg = `Json path <${path}> is not supported in ${mode} environment!` isError ? error(msg) : warn(msg) } - function deletePath(opts) { + function deletePath (opts) { let isError = opts let shouldLog = true if (typeof opts === 'object') { @@ -37,7 +37,7 @@ module.exports = function getSpec({ warn, error }) { * @desc 在app.mpx里配置usingComponents作为全局组件 */ - function addGlobalComponents(input, { globalComponents }) { + function addGlobalComponents (input, { globalComponents }) { if (globalComponents) { input.usingComponents = Object.assign({}, globalComponents, input.usingComponents) } @@ -45,7 +45,7 @@ module.exports = function getSpec({ warn, error }) { } // 处理支付宝 componentPlaceholder 不支持 view、text 原生标签 - function aliComponentPlaceholderFallback(input) { + function aliComponentPlaceholderFallback (input) { // 处理 驼峰转连字符 input = componentNameCapitalToHyphen('componentPlaceholder')(input) const componentPlaceholder = input.componentPlaceholder @@ -70,7 +70,7 @@ module.exports = function getSpec({ warn, error }) { return input } - function fillGlobalComponents(input, { globalComponents }) { + function fillGlobalComponents (input, { globalComponents }) { if (globalComponents) { Object.assign(globalComponents, input.usingComponents) } @@ -78,7 +78,7 @@ module.exports = function getSpec({ warn, error }) { } // 处理 ali swan 的组件名大写字母转连字符:WordExample/wordExample -> word-example - function componentNameCapitalToHyphen(type) { + function componentNameCapitalToHyphen (type) { return function (input) { // 百度和支付宝不支持大写组件标签名,统一转成带“-”和小写的形式。百度自带标签不会有带大写的情况 // 后续可能需要考虑这些平台支持 componentGenerics 后的转换 https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/generics.html @@ -142,13 +142,13 @@ module.exports = function getSpec({ warn, error }) { const windowRules = [ { test: 'navigationBarTitleText', - ali(input) { + ali (input) { return changeKey(input, this.test, 'defaultTitle') } }, { test: 'enablePullDownRefresh', - ali(input) { + ali (input) { input = changeKey(input, this.test, 'pullRefresh') if (input.pullRefresh) { input.allowsBounceVertical = 'YES' @@ -159,7 +159,7 @@ module.exports = function getSpec({ warn, error }) { }, { test: 'navigationBarBackgroundColor', - ali(input) { + ali (input) { return changeKey(input, this.test, 'titleBarColor') } }, @@ -236,19 +236,19 @@ module.exports = function getSpec({ warn, error }) { list: [ { test: 'text', - ali(input) { + ali (input) { return changeKey(input, this.test, 'name') } }, { test: 'iconPath', - ali(input) { + ali (input) { return changeKey(input, this.test, 'icon') } }, { test: 'selectedIconPath', - ali(input) { + ali (input) { return changeKey(input, this.test, 'activeIcon') } } @@ -256,13 +256,13 @@ module.exports = function getSpec({ warn, error }) { rules: [ { test: 'color', - ali(input) { + ali (input) { return changeKey(input, this.test, 'textColor') } }, { test: 'list', - ali(input) { + ali (input) { const value = input.list delete input.list input.items = value.map(item => { From a0d7f0171b8e4535f1962bdb7415fec0d25abe93 Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Thu, 31 Aug 2023 14:10:02 +0800 Subject: [PATCH 29/59] v2.8.42 --- lerna.json | 2 +- packages/core/package.json | 2 +- packages/size-report/package.json | 2 +- packages/webpack-plugin/package.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lerna.json b/lerna.json index d99be26bef..6806b1c213 100644 --- a/lerna.json +++ b/lerna.json @@ -2,5 +2,5 @@ "packages": [ "packages/*" ], - "version": "2.8.41" + "version": "2.8.42" } diff --git a/packages/core/package.json b/packages/core/package.json index 39a4fe13b9..58b5fa94f9 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@mpxjs/core", - "version": "2.8.40", + "version": "2.8.42", "description": "mpx runtime core", "keywords": [ "miniprogram", diff --git a/packages/size-report/package.json b/packages/size-report/package.json index 7df6e86bd4..507021d257 100644 --- a/packages/size-report/package.json +++ b/packages/size-report/package.json @@ -1,6 +1,6 @@ { "name": "@mpxjs/size-report", - "version": "2.8.40", + "version": "2.8.42", "description": "mpx size report plugin", "main": "src/index.js", "scripts": { diff --git a/packages/webpack-plugin/package.json b/packages/webpack-plugin/package.json index 7d1d105f07..30e69e21b9 100644 --- a/packages/webpack-plugin/package.json +++ b/packages/webpack-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@mpxjs/webpack-plugin", - "version": "2.8.41", + "version": "2.8.42", "description": "mpx compile core", "keywords": [ "mpx" From 06d2f9e83cd868c36f1a4f2ded2aacd1e666cee0 Mon Sep 17 00:00:00 2001 From: xuegan Date: Thu, 31 Aug 2023 18:43:00 +0800 Subject: [PATCH 30/59] =?UTF-8?q?fix:=E6=B7=BB=E5=8A=A0placeholder?= =?UTF-8?q?=E7=9A=84=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/webpack-plugin/lib/json-compiler/helper.js | 7 +++++-- packages/webpack-plugin/lib/json-compiler/index.js | 12 ++++++++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/packages/webpack-plugin/lib/json-compiler/helper.js b/packages/webpack-plugin/lib/json-compiler/helper.js index 1e172c87e2..c558c14c79 100644 --- a/packages/webpack-plugin/lib/json-compiler/helper.js +++ b/packages/webpack-plugin/lib/json-compiler/helper.js @@ -51,10 +51,12 @@ module.exports = function createJSONHelper ({ loaderContext, emitWarning, custom resolve(context, component, loaderContext, (err, resource, info) => { if (err) return callback(err) const { resourcePath, queryObj } = parseRequest(resource) - if (!queryObj.root && asyncComponentsConfig) { + let placeholder = null + if (!queryObj.root && asyncComponentsConfig && enableRequireAsync) { asyncComponentsConfig.forEach(item => { if (matchCondition(resourcePath, item)) { queryObj.root = item.root + queryObj.placeholder = item.placeholder } }) } @@ -64,6 +66,7 @@ module.exports = function createJSONHelper ({ loaderContext, emitWarning, custom // 目前只有微信支持分包异步化 if (enableRequireAsync) { tarRoot = queryObj.root + placeholder = queryObj.placeholder } } const parsed = path.parse(resourcePath) @@ -94,7 +97,7 @@ module.exports = function createJSONHelper ({ loaderContext, emitWarning, custom } const entry = getDynamicEntry(resource, 'component', outputPath, tarRoot, relativePath) - callback(null, entry, tarRoot) + callback(null, entry, tarRoot, placeholder) }) } diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index 589b595866..a7df5ad854 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -185,7 +185,7 @@ module.exports = function (content) { const processComponents = (components, context, callback) => { if (components) { async.eachOf(components, (component, name, callback) => { - processComponent(component, context, { relativePath }, (err, entry, root) => { + processComponent(component, context, { relativePath }, (err, entry, root, placeholder) => { if (err === RESOLVE_IGNORED_ERR) { delete components[name] return callback() @@ -193,7 +193,15 @@ module.exports = function (content) { if (err) return callback(err) components[name] = entry if (root) { - if (!json.componentPlaceholder || !json.componentPlaceholder[name]) { + if (placeholder) { + if (json.componentPlaceholder) { + if (!json.componentPlaceholder[name]) json.componentPlaceholder[name] = placeholder + } else { + json.componentPlaceholder = { + [name]: placeholder + } + } + } else if (!json.componentPlaceholder || !json.componentPlaceholder[name]) { const errMsg = `componentPlaceholder of "${name}" doesn't exist! \n\r` emitError(errMsg) } From 8c47373ba3febfddd3beb1beee10c187c0120954 Mon Sep 17 00:00:00 2001 From: xuegan Date: Thu, 31 Aug 2023 19:56:22 +0800 Subject: [PATCH 31/59] =?UTF-8?q?fix:=E6=96=87=E6=A1=A3=E5=86=85=E5=AE=B9?= =?UTF-8?q?=E8=A1=A5=E5=85=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs-vuepress/api/compile.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/docs-vuepress/api/compile.md b/docs-vuepress/api/compile.md index 04252a0188..3034f4baf5 100644 --- a/docs-vuepress/api/compile.md +++ b/docs-vuepress/api/compile.md @@ -1409,6 +1409,7 @@ module.exports = defineConfig({ - **类型**:`Array【{ include: string | RegExp | Function | Array, root: string }】` * include: 同 webpack include 规则 * root: 匹配规则的组件或js模块的输出分包名 + * placeholder: 匹配规则的组件所配置的componentPlaceholder,暂时只支持配置原生组件,若想要配置自定义组件需去组件 json block 中配置 - **详细**:异步分包场景下批量设置组件或 js 模块的异步分包,提升资源异步分包输出的灵活性。 @@ -1420,7 +1421,8 @@ new MpxWebpackPlugin({ asyncComponentsConfig: [ { include: '/project/pages', // 文件路径包含 '/project/pages' 的组件或者 require.async 异步引用的js 模块都会被打包至sub1分包 - root: 'sub1' + root: 'sub1', + placeholder: 'view' } ] }) @@ -1434,10 +1436,11 @@ module.exports = defineConfig({ mpx: { plugin: { // include 可以是正则、字符串、函数、数组 - partialCompile: [ + asyncComponentsConfig: [ { include: '/project/pages', // 文件路径包含 '/project/pages' 的组件或者 require.async 异步引用的js 模块都会被打包至sub1分包 - root: 'sub1' + root: 'sub1', + placeholder: 'view' } ] } @@ -1448,7 +1451,7 @@ module.exports = defineConfig({ ::: :::warning -* 该配置匹配的组件,若使用方在引用路径已设置?root,则以引用路径中的?root为最高优先级 +* 该配置匹配的组件,若使用方在引用路径已设置?root或componentPlaceholder,则以引用路径中的?root或componentPlaceholder为最高优先级 * 本功能默认不会增加componentPlaceholder配置,开启异步分包的组件开发者务必配置componentPlaceholder * 本功能只会对使用require.async异步引用的js模块生效,若引用路径中已配置?root,则以路径中?root优先 ::: From 0cd036690da90e7c240c45591a2f31356e22a3d7 Mon Sep 17 00:00:00 2001 From: anotherso1a <1181581742@qq.com> Date: Fri, 1 Sep 2023 12:02:31 +0800 Subject: [PATCH 32/59] fix: Change the scroll-view attribute binding to adapt to built-in components --- .../platform/template/wx/component-config/scroll-view.js | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/packages/webpack-plugin/lib/platform/template/wx/component-config/scroll-view.js b/packages/webpack-plugin/lib/platform/template/wx/component-config/scroll-view.js index 1e6e4a2fde..19adae3344 100644 --- a/packages/webpack-plugin/lib/platform/template/wx/component-config/scroll-view.js +++ b/packages/webpack-plugin/lib/platform/template/wx/component-config/scroll-view.js @@ -20,6 +20,15 @@ module.exports = function ({ print }) { return 'mpx-scroll-view' }, props: [ + { + test: /^(scroll-x|scroll-y|scroll-with-animation|enable-flex|enhanced|refresher-enabled|refresher-triggered)$/, + web ({ name, value = 'true' }) { // value is undefined, value is true. eg: + return { + name: `:${name}`, // make props binding + value + } + } + }, { test: /^(enable-flex|scroll-anchorin|refresher-enabled|refresher-threshold|refresher-default-style|refresher-background|refresher-triggered|enhanced|bounces|show-scrollbar|paging-enabled|fast-deceleratio)$/, ali: aliPropLog, From f6c9b4678891bf8ffe88020e710699ffd1715718 Mon Sep 17 00:00:00 2001 From: xuegan Date: Sat, 2 Sep 2023 21:59:16 +0800 Subject: [PATCH 33/59] =?UTF-8?q?feat:=E5=88=A0=E9=99=A4=E7=9B=B4=E6=8E=A5?= =?UTF-8?q?=E4=BF=AE=E6=94=B9queryObj=E7=9A=84=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs-vuepress/api/compile.md | 6 ++--- packages/webpack-plugin/lib/index.js | 24 +++++++------------ .../lib/json-compiler/helper.js | 20 +++++++--------- 3 files changed, 21 insertions(+), 29 deletions(-) diff --git a/docs-vuepress/api/compile.md b/docs-vuepress/api/compile.md index 3034f4baf5..c3c88959ba 100644 --- a/docs-vuepress/api/compile.md +++ b/docs-vuepress/api/compile.md @@ -1404,7 +1404,7 @@ module.exports = defineConfig({ 该特性只能用于**开发环境**,默认情况下会阻止所有页面(**入口 app.mpx 除外**)的打包。 ::: -### asyncComponentsConfig +### asyncSubpackageRules - **类型**:`Array【{ include: string | RegExp | Function | Array, root: string }】` * include: 同 webpack include 规则 @@ -1418,7 +1418,7 @@ module.exports = defineConfig({ ```js // include 可以是正则、字符串、函数、数组 new MpxWebpackPlugin({ - asyncComponentsConfig: [ + asyncSubpackageRules: [ { include: '/project/pages', // 文件路径包含 '/project/pages' 的组件或者 require.async 异步引用的js 模块都会被打包至sub1分包 root: 'sub1', @@ -1436,7 +1436,7 @@ module.exports = defineConfig({ mpx: { plugin: { // include 可以是正则、字符串、函数、数组 - asyncComponentsConfig: [ + asyncSubpackageRules: [ { include: '/project/pages', // 文件路径包含 '/project/pages' 的组件或者 require.async 异步引用的js 模块都会被打包至sub1分包 root: 'sub1', diff --git a/packages/webpack-plugin/lib/index.js b/packages/webpack-plugin/lib/index.js index 23d644b051..80860181b2 100644 --- a/packages/webpack-plugin/lib/index.js +++ b/packages/webpack-plugin/lib/index.js @@ -167,7 +167,7 @@ class MpxWebpackPlugin { }, options.nativeConfig) options.webConfig = options.webConfig || {} options.partialCompile = options.mode !== 'web' && options.partialCompile - options.asyncComponentsConfig = options.asyncComponentsConfig || null + options.asyncSubpackageRules = options.asyncSubpackageRules || null options.retryRequireAsync = options.retryRequireAsync || false options.enableAliRequireAsync = options.enableAliRequireAsync || false this.options = options @@ -398,18 +398,11 @@ class MpxWebpackPlugin { if (obj.path.startsWith(require.resolve('./json-compiler/default-page.mpx'))) { return callback(null, obj) } - const infix = obj.query ? '&' : '?' if (isResolvingPage(obj) && !matchCondition(obj.path, this.options.partialCompile)) { + const infix = obj.query ? '&' : '?' obj.query += `${infix}resourcePath=${obj.path}` obj.path = require.resolve('./json-compiler/default-page.mpx') } - // if (isResolvingComponent(obj)) { - // this.options.asyncComponentsConfig.forEach(item => { - // if (matchCondition(obj.path, item)) { - // obj.query += `${infix}root=${item.root}&placeholder=${item.placeholder}` - // } - // }) - // } callback(null, obj) }) }) @@ -630,7 +623,7 @@ class MpxWebpackPlugin { forceProxyEventRules: this.options.forceProxyEventRules, enableRequireAsync: this.options.mode === 'wx' || (this.options.mode === 'ali' && this.options.enableAliRequireAsync), partialCompile: this.options.partialCompile, - asyncComponentsConfig: this.options.asyncComponentsConfig, + asyncSubpackageRules: this.options.asyncSubpackageRules, pathHash: (resourcePath) => { if (this.options.pathHashMode === 'relative' && this.options.projectRoot) { return hash(path.relative(this.options.projectRoot, resourcePath)) @@ -1036,19 +1029,20 @@ class MpxWebpackPlugin { const range = expr.arguments[0].range const context = parser.state.module.context const { queryObj, resourcePath } = parseRequest(request) - if (!queryObj.root && mpx.asyncComponentsConfig) { - mpx.asyncComponentsConfig.forEach(item => { + let tarRoot = queryObj.root + if (!queryObj.root && mpx.asyncSubpackageRules) { + mpx.asyncSubpackageRules.forEach(item => { if (matchCondition(resourcePath, item)) { - queryObj.root = item.root + tarRoot = item.root } }) } - if (queryObj.root) { + if (tarRoot) { // 删除root query request = addQuery(request, {}, false, ['root']) // 目前仅wx和ali支持require.async,ali需要开启enableAliRequireAsync,其余平台使用CommonJsAsyncDependency进行模拟抹平 if (mpx.enableRequireAsync) { - const dep = new DynamicEntryDependency(request, 'export', '', queryObj.root, '', context, range, { + const dep = new DynamicEntryDependency(request, 'export', '', tarRoot, '', context, range, { isRequireAsync: true, retryRequireAsync: !!this.options.retryRequireAsync }) diff --git a/packages/webpack-plugin/lib/json-compiler/helper.js b/packages/webpack-plugin/lib/json-compiler/helper.js index c558c14c79..43d0250238 100644 --- a/packages/webpack-plugin/lib/json-compiler/helper.js +++ b/packages/webpack-plugin/lib/json-compiler/helper.js @@ -18,7 +18,7 @@ module.exports = function createJSONHelper ({ loaderContext, emitWarning, custom const getOutputPath = mpx.getOutputPath const mode = mpx.mode const enableRequireAsync = mpx.enableRequireAsync - const asyncComponentsConfig = mpx.asyncComponentsConfig + const asyncSubpackageRules = mpx.asyncSubpackageRules const isUrlRequest = r => isUrlRequestRaw(r, root, externals) const urlToRequest = r => loaderUtils.urlToRequest(r) @@ -47,28 +47,26 @@ module.exports = function createJSONHelper ({ loaderContext, emitWarning, custom if (resolveMode === 'native') { component = urlToRequest(component) } - component = addQuery(component, { isComponent: true }) resolve(context, component, loaderContext, (err, resource, info) => { if (err) return callback(err) const { resourcePath, queryObj } = parseRequest(resource) let placeholder = null - if (!queryObj.root && asyncComponentsConfig && enableRequireAsync) { - asyncComponentsConfig.forEach(item => { - if (matchCondition(resourcePath, item)) { - queryObj.root = item.root - queryObj.placeholder = item.placeholder - } - }) - } if (queryObj.root) { // 删除root query resource = addQuery(resource, {}, false, ['root']) // 目前只有微信支持分包异步化 if (enableRequireAsync) { tarRoot = queryObj.root - placeholder = queryObj.placeholder } + } else if (!queryObj.root && asyncSubpackageRules && enableRequireAsync) { + asyncSubpackageRules.forEach(item => { + if (matchCondition(resourcePath, item)) { + tarRoot = item.root + placeholder = item.placeholder + } + }) } + const parsed = path.parse(resourcePath) const ext = parsed.ext const resourceName = path.join(parsed.dir, parsed.name) From a04dd211b34b289f782775058ed7dcb630fea3ff Mon Sep 17 00:00:00 2001 From: xuegan Date: Tue, 5 Sep 2023 17:50:45 +0800 Subject: [PATCH 34/59] =?UTF-8?q?feat:=E8=87=AA=E5=AE=9A=E4=B9=89=E5=BC=82?= =?UTF-8?q?=E6=AD=A5=E7=BB=84=E4=BB=B6=E6=94=AF=E6=8C=81=E8=87=AA=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E7=BB=84=E4=BB=B6=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../webpack-plugin/lib/json-compiler/index.js | 38 ++++++++++++++++--- packages/webpack-plugin/lib/runtime/base.styl | 5 --- 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index a7df5ad854..2d3e7ee1a2 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -194,19 +194,45 @@ module.exports = function (content) { components[name] = entry if (root) { if (placeholder) { - if (json.componentPlaceholder) { - if (!json.componentPlaceholder[name]) json.componentPlaceholder[name] = placeholder - } else { - json.componentPlaceholder = { - [name]: placeholder + function fillInComponentPlaceholder (resource) { + if (json.componentPlaceholder) { + if (!json.componentPlaceholder[name]) json.componentPlaceholder[name] = resource + } else { + json.componentPlaceholder = { + [name]: resource + } + } + } + function normalizePlaceholder(placeholder) { + if (typeof placeholder === 'string') { + placeholder = { + resource: placeholder + } } + if (!placeholder.resource) { + emitError(`The asyncSubpackageRules configuration format of @mpxjs/webpack-plugin a is incorrect`) + } + return placeholder + } + placeholder = normalizePlaceholder(placeholder) + if (placeholder.name === 'custom') { + processComponent(placeholder.resource, context, { relativePath },(err, entry) => { + if (err) return callback(err) + fillInComponentPlaceholder(entry) + callback() + }) + } else { + fillInComponentPlaceholder(placeholder.resource) + callback() } } else if (!json.componentPlaceholder || !json.componentPlaceholder[name]) { const errMsg = `componentPlaceholder of "${name}" doesn't exist! \n\r` emitError(errMsg) + callback() } + } else { + callback() } - callback() }) }, callback) } else { diff --git a/packages/webpack-plugin/lib/runtime/base.styl b/packages/webpack-plugin/lib/runtime/base.styl index 1796bab6db..38b6414eb7 100644 --- a/packages/webpack-plugin/lib/runtime/base.styl +++ b/packages/webpack-plugin/lib/runtime/base.styl @@ -120,8 +120,3 @@ html, body, .app { font-family "weui" src url('data:application/octet-stream;base64,AAEAAAALAIAAAwAwR1NVQrD+s+0AAAE4AAAAQk9TLzJAKEx+AAABfAAAAFZjbWFw65cFHQAAAhwAAAJQZ2x5ZvCRR/EAAASUAAAKtGhlYWQLKIN9AAAA4AAAADZoaGVhCCwD+gAAALwAAAAkaG10eEJo//8AAAHUAAAASGxvY2EYqhW6AAAEbAAAACZtYXhwASEAVQAAARgAAAAgbmFtZeNcHtgAAA9IAAAB5nBvc3T6bLhLAAARMAAAAOYAAQAAA+gAAABaA+j/////A+kAAQAAAAAAAAAAAAAAAAAAABIAAQAAAAEAACkCj3dfDzz1AAsD6AAAAADUER9XAAAAANQRH1f//wAAA+kD6gAAAAgAAgAAAAAAAAABAAAAEgBJAAUAAAAAAAIAAAAKAAoAAAD/AAAAAAAAAAEAAAAKAB4ALAABREZMVAAIAAQAAAAAAAAAAQAAAAFsaWdhAAgAAAABAAAAAQAEAAQAAAABAAgAAQAGAAAAAQAAAAAAAQOwAZAABQAIAnoCvAAAAIwCegK8AAAB4AAxAQIAAAIABQMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUGZFZABA6gHqEQPoAAAAWgPqAAAAAAABAAAAAAAAAAAAAAPoAAAD6AAAA+gAAAPoAAAD6AAAA+gAAAPoAAAD6AAAA+gAAAPoAAAD6AAAA+gAAAPoAAAD6AAAA+j//wPoAAAD6AAAAAAABQAAAAMAAAAsAAAABAAAAXQAAQAAAAAAbgADAAEAAAAsAAMACgAAAXQABABCAAAABAAEAAEAAOoR//8AAOoB//8AAAABAAQAAAABAAIAAwAEAAUABgAHAAgACQAKAAsADAANAA4ADwAQABEAAAEGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAANwAAAAAAAAAEQAA6gEAAOoBAAAAAQAA6gIAAOoCAAAAAgAA6gMAAOoDAAAAAwAA6gQAAOoEAAAABAAA6gUAAOoFAAAABQAA6gYAAOoGAAAABgAA6gcAAOoHAAAABwAA6ggAAOoIAAAACAAA6gkAAOoJAAAACQAA6goAAOoKAAAACgAA6gsAAOoLAAAACwAA6gwAAOoMAAAADAAA6g0AAOoNAAAADQAA6g4AAOoOAAAADgAA6g8AAOoPAAAADwAA6hAAAOoQAAAAEAAA6hEAAOoRAAAAEQAAAAAARgCMANIBJgF4AcQCMgJgAqgC/ANIA6YD/gROBKAE9AVaAAAAAgAAAAADrwOtABQAKQAAASIHBgcGFBcWFxYyNzY3NjQnJicmAyInJicmNDc2NzYyFxYXFhQHBgcGAfV4Z2Q7PDw7ZGfwZmQ7PDw7ZGZ4bl5bNjc3Nlte215bNjc3NlteA608O2Rn8GdjOzw8O2Nn8GdkOzz8rzc1W17bXlw1Nzc1XF7bXls1NwAAAAACAAAAAAOzA7MAFwAtAAABIgcGBwYVFBcWFxYzMjc2NzY1NCcmJyYTBwYiLwEmNjsBETQ2OwEyFhURMzIWAe52Z2Q7PT07ZGd2fGpmOz4+O2ZpIXYOKA52Dg0XXQsHJgcLXRcNA7M+O2ZqfHZnZDs9PTtkZ3Z9aWY7Pv3wmhISmhIaARcICwsI/ukaAAMAAAAAA+UD5QAXACMALAAAASIHBgcGFRQXFhcWMzI3Njc2NTQnJicmAxQrASI1AzQ7ATIHJyImNDYyFhQGAe6Ecm9BRERBb3KEiXZxQkREQnF1aQIxAwgCQgMBIxIZGSQZGQPkREJxdomEcm9BRERBb3KEinVxQkT9HQICAWICAjEZIxkZIxkAAAAAAwAAAAADsQPkABsAKgAzAAABBgcGBwYHBjcRFBcWFxYXNjc2NzY1ESQXJicmBzMyFhUDFAYrASInAzQ2EyImNDYyFhQGAfVBQTg7LDt/IEc+bF5sbF1tPUj+2KhQQVVvNAQGDAMCJgUBCwYeDxYWHhUVA+QPEg4SDhIpCv6tj3VkST4dHT5JZHWPAVNeNRkSGPwGBP7GAgMFAToEBv5AFR8VFR8VAAAAAgAAAAADsQPkABkALgAAAQYHBgc2BREUFxYXFhc2NzY3NjURJBcmJyYTAQYvASY/ATYyHwEWNjclNjIfARYB9VVVQk+v/tFHPmxebGxdbT1I/tGvT0JVo/7VBASKAwMSAQUBcQEFAgESAgUBEQQD4xMYEhk3YP6sjnVlSD8cHD9IZXWOAVRgNxkSGP62/tkDA48EBBkCAVYCAQHlAQIQBAAAAAACAAAAAAPkA+QAFwAtAAABIgcGBwYVFBcWFxYzMjc2NzY1NCcmJyYTAQYiLwEmPwE2Mh8BFjI3ATYyHwEWAe6Ecm9BQ0NCbnODiXVxQkREQnF1kf6gAQUBowMDFgEFAYUCBQEBQwIFARUEA+NEQnF1iYNzbkJDQ0FvcoSJdXFCRP6j/qUBAagEBR4CAWYBAQENAgIVBAAAAAQAAAAAA68DrQAUACkAPwBDAAABIgcGBwYUFxYXFjI3Njc2NCcmJyYDIicmJyY0NzY3NjIXFhcWFAcGBwYTBQ4BLwEmBg8BBhYfARYyNwE+ASYiFzAfAQH1eGdkOzw8O2Rn8GZkOzw8O2RmeG5eWzY3NzZbXtteWzY3NzZbXmn+9gYSBmAGDwUDBQEGfQUQBgElBQELEBUBAQOtPDtkZ/BnYzs8PDtjZ/BnZDs8/K83NVte215cNTc3NVxe215bNTcCJt0FAQVJBQIGBAcRBoAGBQEhBQ8LBAEBAAABAAAAAAO7AzoAFwAAEy4BPwE+AR8BFjY3ATYWFycWFAcBBiInPQoGBwUHGgzLDCELAh0LHwsNCgr9uQoeCgGzCyEOCw0HCZMJAQoBvgkCCg0LHQv9sQsKAAAAAAIAAAAAA+UD5gAXACwAAAEiBwYHBhUUFxYXFjMyNzY3NjU0JyYnJhMHBi8BJicmNRM0NjsBMhYVExceAQHvhHJvQUNDQm5zg4l1cUJEREJxdVcQAwT6AwIEEAMCKwIDDsUCAQPlREJxdYmDc25CQ0NBb3KEiXVxQkT9VhwEAncCAgMGAXoCAwMC/q2FAgQAAAQAAAAAA68DrQADABgALQAzAAABMB8BAyIHBgcGFBcWFxYyNzY3NjQnJicmAyInJicmNDc2NzYyFxYXFhQHBgcGAyMVMzUjAuUBAfJ4Z2Q7PDw7ZGfwZmQ7PDw7ZGZ4bl5bNjc3Nlte215bNjc3NltemyT92QKDAQEBLDw7ZGfwZ2M7PDw7Y2fwZ2Q7PPyvNzVbXtteXDU3NzVcXtteWzU3AjH9JAAAAAMAAAAAA+QD5AAXACcAMAAAASIHBgcGFRQXFhcWMzI3Njc2NTQnJicmAzMyFhUDFAYrASImNQM0NhMiJjQ2MhYUBgHuhHJvQUNDQm5zg4l1cUJEREJxdZ42BAYMAwInAwMMBh8PFhYeFhYD40RCcXWJg3NuQkNDQW9yhIl1cUJE/vYGBf7AAgMDAgFABQb+NhYfFhYfFgAABAAAAAADwAPAAAgAEgAoAD0AAAEyNjQmIgYUFhcjFTMRIxUzNSMDIgcGBwYVFBYXFjMyNzY3NjU0Jy4BAyInJicmNDc2NzYyFxYXFhQHBgcGAfQYISEwISFRjzk5yTorhG5rPT99am+DdmhlPD4+PMyFbV5bNTc3NVte2l5bNTc3NVteAqAiLyIiLyI5Hf7EHBwCsT89a26Ed8w8Pj48ZWh2g29qffyjNzVbXtpeWzU3NzVbXtpeWzU3AAADAAAAAAOoA6gACwAgADUAAAEHJwcXBxc3FzcnNwMiBwYHBhQXFhcWMjc2NzY0JyYnJgMiJyYnJjQ3Njc2MhcWFxYUBwYHBgKOmpocmpocmpocmpq2dmZiOjs7OmJm7GZiOjs7OmJmdmtdWTQ2NjRZXdZdWTQ2NjRZXQKqmpocmpocmpocmpoBGTs6YmbsZmI6Ozs6YmbsZmI6O/zCNjRZXdZdWTQ2NjRZXdZdWTQ2AAMAAAAAA+kD6gAaAC8AMAAAAQYHBiMiJyYnJjQ3Njc2MhcWFxYVFAcGBwEHATI3Njc2NCcmJyYiBwYHBhQXFhcWMwKONUBCR21dWjU3NzVaXdpdWzU2GBcrASM5/eBXS0grKysrSEuuSkkqLCwqSUpXASMrFxg2NVtd2l1aNTc3NVpdbUdCQDX+3jkBGSsrSEuuSkkqLCwqSUquS0grKwAC//8AAAPoA+gAFAAwAAABIgcGBwYQFxYXFiA3Njc2ECcmJyYTFg4BIi8BBwYuATQ/AScmPgEWHwE3Nh4BBg8BAfSIdHFDRERDcXQBEHRxQ0REQ3F0SQoBFBsKoqgKGxMKqKIKARQbCqKoChsUAQqoA+hEQ3F0/vB0cUNERENxdAEQdHFDRP1jChsTCqiiCgEUGwqiqAobFAEKqKIKARQbCqIAAAIAAAAAA+QD5AAXADQAAAEiBwYHBhUUFxYXFjMyNzY3NjU0JyYnJhMUBiMFFxYUDwEGLwEuAT8BNh8BFhQPAQUyFh0BAe6Ecm9BQ0NCbnODiXVxQkREQnF1fwQC/pGDAQEVAwTsAgEC7AQEFAIBhAFwAgMD40RCcXWJg3NuQkNDQW9yhIl1cUJE/fYCAwuVAgQCFAQE0AIFAtEEBBQCBQGVCwMDJwAAAAUAAAAAA9QD0wAjACcANwBHAEgAAAERFAYjISImNREjIiY9ATQ2MyE1NDYzITIWHQEhMhYdARQGIyERIREHIgYVERQWOwEyNjURNCYjISIGFREUFjsBMjY1ETQmKwEDeyYb/XYbJkMJDQ0JAQYZEgEvExkBBgkNDQn9CQJc0QkNDQktCQ0NCf7sCQ0NCS0JDQ0JLQMi/TQbJiYbAswMCiwJDS4SGRkSLg0JLAoM/UwCtGsNCf5NCQ0NCQGzCQ0NCf5NCQ0NCQGzCQ0AAAAAEADGAAEAAAAAAAEABAAAAAEAAAAAAAIABwAEAAEAAAAAAAMABAALAAEAAAAAAAQABAAPAAEAAAAAAAUACwATAAEAAAAAAAYABAAeAAEAAAAAAAoAKwAiAAEAAAAAAAsAEwBNAAMAAQQJAAEACABgAAMAAQQJAAIADgBoAAMAAQQJAAMACAB2AAMAAQQJAAQACAB+AAMAAQQJAAUAFgCGAAMAAQQJAAYACACcAAMAAQQJAAoAVgCkAAMAAQQJAAsAJgD6d2V1aVJlZ3VsYXJ3ZXVpd2V1aVZlcnNpb24gMS4wd2V1aUdlbmVyYXRlZCBieSBzdmcydHRmIGZyb20gRm9udGVsbG8gcHJvamVjdC5odHRwOi8vZm9udGVsbG8uY29tAHcAZQB1AGkAUgBlAGcAdQBsAGEAcgB3AGUAdQBpAHcAZQB1AGkAVgBlAHIAcwBpAG8AbgAgADEALgAwAHcAZQB1AGkARwBlAG4AZQByAGEAdABlAGQAIABiAHkAIABzAHYAZwAyAHQAdABmACAAZgByAG8AbQAgAEYAbwBuAHQAZQBsAGwAbwAgAHAAcgBvAGoAZQBjAHQALgBoAHQAdABwADoALwAvAGYAbwBuAHQAZQBsAGwAbwAuAGMAbwBtAAAAAgAAAAAAAAAKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAQIBAwEEAQUBBgEHAQgBCQEKAQsBDAENAQ4BDwEQAREBEgETAAZjaXJjbGUIZG93bmxvYWQEaW5mbwxzYWZlX3N1Y2Nlc3MJc2FmZV93YXJuB3N1Y2Nlc3MOc3VjY2Vzcy1jaXJjbGURc3VjY2Vzcy1uby1jaXJjbGUHd2FpdGluZw53YWl0aW5nLWNpcmNsZQR3YXJuC2luZm8tY2lyY2xlBmNhbmNlbAZzZWFyY2gFY2xlYXIEYmFjawZkZWxldGUAAAAA') format('truetype') } - -.mpx-root-view { - display: inline - line-height: normal -} \ No newline at end of file From cc111a945f881f12698a16c36ac10c69175d4391 Mon Sep 17 00:00:00 2001 From: xuegan Date: Tue, 5 Sep 2023 17:54:48 +0800 Subject: [PATCH 35/59] fix:lint error --- packages/webpack-plugin/lib/json-compiler/index.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index 2d3e7ee1a2..cc5d9f2b2e 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -203,20 +203,20 @@ module.exports = function (content) { } } } - function normalizePlaceholder(placeholder) { + function normalizePlaceholder (placeholder) { if (typeof placeholder === 'string') { - placeholder = { + placeholder = { resource: placeholder } } if (!placeholder.resource) { - emitError(`The asyncSubpackageRules configuration format of @mpxjs/webpack-plugin a is incorrect`) + emitError('The asyncSubpackageRules configuration format of @mpxjs/webpack-plugin a is incorrect') } return placeholder } placeholder = normalizePlaceholder(placeholder) if (placeholder.name === 'custom') { - processComponent(placeholder.resource, context, { relativePath },(err, entry) => { + processComponent(placeholder.resource, context, { relativePath }, (err, entry) => { if (err) return callback(err) fillInComponentPlaceholder(entry) callback() From 23d5975480c7c5c760697fc5c9d6fa8a77d83ed3 Mon Sep 17 00:00:00 2001 From: xuegan Date: Tue, 5 Sep 2023 18:11:53 +0800 Subject: [PATCH 36/59] =?UTF-8?q?docs:=E8=A1=A5=E5=85=85=E7=9B=B8=E5=85=B3?= =?UTF-8?q?=E6=96=87=E6=A1=A3=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs-vuepress/api/compile.md | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/docs-vuepress/api/compile.md b/docs-vuepress/api/compile.md index c3c88959ba..e621328e44 100644 --- a/docs-vuepress/api/compile.md +++ b/docs-vuepress/api/compile.md @@ -1406,10 +1406,21 @@ module.exports = defineConfig({ ### asyncSubpackageRules -- **类型**:`Array【{ include: string | RegExp | Function | Array, root: string }】` +- **类型**: + ```ts +type Condition = string | Function | RegExp + +interface AsyncSubpackageRules { + include: Condition | Array + exclude?: Condition | Array + root: string + placeholder: string | { name?: string, resource: string} +} +``` * include: 同 webpack include 规则 + * exclude: 同 webpack exclude 规则 * root: 匹配规则的组件或js模块的输出分包名 - * placeholder: 匹配规则的组件所配置的componentPlaceholder,暂时只支持配置原生组件,若想要配置自定义组件需去组件 json block 中配置 + * placeholder: 匹配规则的组件所配置的componentPlaceholder,可支持配置原生组件和自定义组件,原生组件可直接以string类型配置,自定义组件需要配置对象,name 需设置为 **custom**, resource为自定义组件的绝对路径 - **详细**:异步分包场景下批量设置组件或 js 模块的异步分包,提升资源异步分包输出的灵活性。 @@ -1426,6 +1437,19 @@ new MpxWebpackPlugin({ } ] }) +// 若配置自定义组件 +new MpxWebpackPlugin({ + asyncSubpackageRules: [ + { + include: '/project/pages', // 文件路径包含 '/project/pages' 的组件或者 require.async 异步引用的js 模块都会被打包至sub1分包 + root: 'sub1', + placeholder: { + name: 'custom', + resource: '/user/xxxx/index.mpx' // 自定义组件的绝对路径 + } + } + ] +}) ``` ::: tip @mpxjs/cli@3.x 版本配置如下 From fd3cc7ceb9358a1e3ea1e2d75d495ea4ac579815 Mon Sep 17 00:00:00 2001 From: xuegan Date: Tue, 5 Sep 2023 20:32:20 +0800 Subject: [PATCH 37/59] =?UTF-8?q?fix:=E4=BF=AE=E5=A4=8D=E8=87=AA=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E7=BB=84=E4=BB=B6=E9=80=BB=E8=BE=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/webpack-plugin/lib/index.js | 9 ++++---- .../lib/json-compiler/helper.js | 5 ++-- .../webpack-plugin/lib/json-compiler/index.js | 23 ++++++++++++------- 3 files changed, 23 insertions(+), 14 deletions(-) diff --git a/packages/webpack-plugin/lib/index.js b/packages/webpack-plugin/lib/index.js index 80860181b2..9d73eea362 100644 --- a/packages/webpack-plugin/lib/index.js +++ b/packages/webpack-plugin/lib/index.js @@ -1030,16 +1030,17 @@ class MpxWebpackPlugin { const context = parser.state.module.context const { queryObj, resourcePath } = parseRequest(request) let tarRoot = queryObj.root - if (!queryObj.root && mpx.asyncSubpackageRules) { - mpx.asyncSubpackageRules.forEach(item => { + if (!tarRoot && mpx.asyncSubpackageRules) { + for (const item of mpx.asyncSubpackageRules) { if (matchCondition(resourcePath, item)) { tarRoot = item.root + break } - }) + } } if (tarRoot) { // 删除root query - request = addQuery(request, {}, false, ['root']) + if (queryObj.root) request = addQuery(request, {}, false, ['root']) // 目前仅wx和ali支持require.async,ali需要开启enableAliRequireAsync,其余平台使用CommonJsAsyncDependency进行模拟抹平 if (mpx.enableRequireAsync) { const dep = new DynamicEntryDependency(request, 'export', '', tarRoot, '', context, range, { diff --git a/packages/webpack-plugin/lib/json-compiler/helper.js b/packages/webpack-plugin/lib/json-compiler/helper.js index 43d0250238..de64a50d3d 100644 --- a/packages/webpack-plugin/lib/json-compiler/helper.js +++ b/packages/webpack-plugin/lib/json-compiler/helper.js @@ -59,12 +59,13 @@ module.exports = function createJSONHelper ({ loaderContext, emitWarning, custom tarRoot = queryObj.root } } else if (!queryObj.root && asyncSubpackageRules && enableRequireAsync) { - asyncSubpackageRules.forEach(item => { + for (const item of asyncSubpackageRules) { if (matchCondition(resourcePath, item)) { tarRoot = item.root placeholder = item.placeholder + break } - }) + } } const parsed = path.parse(resourcePath) diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index cc5d9f2b2e..dc84e7a991 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -38,6 +38,7 @@ module.exports = function (content) { const globalSrcMode = mpx.srcMode const localSrcMode = queryObj.mode const srcMode = localSrcMode || globalSrcMode + const projectRoot = mpx.projectRoot const isApp = !(pagesMap[resourcePath] || componentsMap[resourcePath]) const publicPath = this._compilation.outputOptions.publicPath || '' @@ -194,19 +195,25 @@ module.exports = function (content) { components[name] = entry if (root) { if (placeholder) { - function fillInComponentPlaceholder (resource) { + function fillInComponentPlaceholder (placeholderName, resource) { + if (resource) { + // 自定义组件 + if (!json.usingComponents[placeholderName]) { + json.usingComponents[placeholderName] = resource + } + } if (json.componentPlaceholder) { - if (!json.componentPlaceholder[name]) json.componentPlaceholder[name] = resource + if (!json.componentPlaceholder[name]) json.componentPlaceholder[name] = placeholderName } else { json.componentPlaceholder = { - [name]: resource + [name]: placeholderName } } } function normalizePlaceholder (placeholder) { if (typeof placeholder === 'string') { placeholder = { - resource: placeholder + name: placeholder } } if (!placeholder.resource) { @@ -215,14 +222,14 @@ module.exports = function (content) { return placeholder } placeholder = normalizePlaceholder(placeholder) - if (placeholder.name === 'custom') { - processComponent(placeholder.resource, context, { relativePath }, (err, entry) => { + if (placeholder.resource) { + processComponent(placeholder.resource, projectRoot, { relativePath }, (err, entry) => { if (err) return callback(err) - fillInComponentPlaceholder(entry) + fillInComponentPlaceholder(placeholder.name, entry) callback() }) } else { - fillInComponentPlaceholder(placeholder.resource) + fillInComponentPlaceholder(placeholder.name) callback() } } else if (!json.componentPlaceholder || !json.componentPlaceholder[name]) { From 7e360067fb5828b9fa215be0ce908a487b5bfb32 Mon Sep 17 00:00:00 2001 From: xuegan Date: Tue, 5 Sep 2023 21:32:35 +0800 Subject: [PATCH 38/59] =?UTF-8?q?fix:=E4=BF=AE=E5=A4=8D=E6=8A=A5=E9=94=99?= =?UTF-8?q?=E5=88=A4=E6=96=AD=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs-vuepress/api/compile.md | 10 +++++----- packages/webpack-plugin/lib/json-compiler/index.js | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs-vuepress/api/compile.md b/docs-vuepress/api/compile.md index e621328e44..422bba38e8 100644 --- a/docs-vuepress/api/compile.md +++ b/docs-vuepress/api/compile.md @@ -1414,13 +1414,13 @@ interface AsyncSubpackageRules { include: Condition | Array exclude?: Condition | Array root: string - placeholder: string | { name?: string, resource: string} + placeholder: string | { name: string, resource?: string} } ``` * include: 同 webpack include 规则 * exclude: 同 webpack exclude 规则 * root: 匹配规则的组件或js模块的输出分包名 - * placeholder: 匹配规则的组件所配置的componentPlaceholder,可支持配置原生组件和自定义组件,原生组件可直接以string类型配置,自定义组件需要配置对象,name 需设置为 **custom**, resource为自定义组件的绝对路径 + * placeholder: 匹配规则的组件所配置的componentPlaceholder,可支持配置原生组件和自定义组件,原生组件可直接以string类型配置,自定义组件需要配置对象,name 为该自定义组件名, resource 为自定义组件的路径,路径可为绝对路径和相对于项目目录的相对路径 - **详细**:异步分包场景下批量设置组件或 js 模块的异步分包,提升资源异步分包输出的灵活性。 @@ -1444,8 +1444,8 @@ new MpxWebpackPlugin({ include: '/project/pages', // 文件路径包含 '/project/pages' 的组件或者 require.async 异步引用的js 模块都会被打包至sub1分包 root: 'sub1', placeholder: { - name: 'custom', - resource: '/user/xxxx/index.mpx' // 自定义组件的绝对路径 + name: 'other-placeholder', + resource: '/user/xxxx/other.mpx' // 自定义组件的绝对路径 } } ] @@ -1476,7 +1476,7 @@ module.exports = defineConfig({ :::warning * 该配置匹配的组件,若使用方在引用路径已设置?root或componentPlaceholder,则以引用路径中的?root或componentPlaceholder为最高优先级 -* 本功能默认不会增加componentPlaceholder配置,开启异步分包的组件开发者务必配置componentPlaceholder +* 若placeholder配置使用自定义组件,注意一定要配置 placeholder 中的 resource 字段 * 本功能只会对使用require.async异步引用的js模块生效,若引用路径中已配置?root,则以路径中?root优先 ::: diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index dc84e7a991..f1fb61a53f 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -216,7 +216,7 @@ module.exports = function (content) { name: placeholder } } - if (!placeholder.resource) { + if (!placeholder.name) { emitError('The asyncSubpackageRules configuration format of @mpxjs/webpack-plugin a is incorrect') } return placeholder From 6df6a5348699360d1bbc4ec80c546590eda4dee6 Mon Sep 17 00:00:00 2001 From: anotherso1a <1181581742@qq.com> Date: Wed, 6 Sep 2023 15:19:49 +0800 Subject: [PATCH 39/59] fix(web): fix web scroll-view's scrollIntoView error --- .../lib/runtime/components/web/mpx-scroll-view.vue | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/web/mpx-scroll-view.vue b/packages/webpack-plugin/lib/runtime/components/web/mpx-scroll-view.vue index 3a10e80e6c..c22c4d312c 100644 --- a/packages/webpack-plugin/lib/runtime/components/web/mpx-scroll-view.vue +++ b/packages/webpack-plugin/lib/runtime/components/web/mpx-scroll-view.vue @@ -113,7 +113,7 @@ }, watch: { scrollIntoView (val) { - this.bs && this.bs.scrollToElement('#' + val, this.scrollWithAnimation ? 200 : 0) + this.scrollToView(val, this.scrollWithAnimation ? 200 : 0) }, _scrollTop (val) { this.bs && this.bs.scrollTo(this.bs.x, -val, this.scrollWithAnimation ? 200 : 0) @@ -201,9 +201,7 @@ leading: true, trailing: false })) - if (this.scrollIntoView) { - this.bs.scrollToElement('#' + this.scrollIntoView) - } + if (this.scrollIntoView) this.scrollToView(this.scrollIntoView) // 若开启自定义下拉刷新 或 开启 scroll-view 增强特性 if (this.refresherEnabled || this.enhanced) { const actionsHandlerHooks = this.bs.scroller.actionsHandler.hooks @@ -258,6 +256,12 @@ } } }, + scrollToView (id, duration = 0) { + if (!id) return + id = id.replace(/^(?!#)/, '#') // 没有 # 的 id 补上 #,有 # 的忽略 + if (!document.querySelector(id)) return // 不存在元素时阻断,直接调用better-scroll的方法会报错 + this.bs.scrollToElement(id, duration) + }, initLayerComputed () { const wrapper = this.$refs.wrapper const wrapperWidth = wrapper.offsetWidth From e44f030541917abad15c239c7e001f6214c8771a Mon Sep 17 00:00:00 2001 From: anotherso1a <1181581742@qq.com> Date: Wed, 6 Sep 2023 15:35:47 +0800 Subject: [PATCH 40/59] revert: remove scroll-view rule change --- .../platform/template/wx/component-config/scroll-view.js | 9 --------- .../lib/runtime/components/web/mpx-scroll-view.vue | 2 +- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/packages/webpack-plugin/lib/platform/template/wx/component-config/scroll-view.js b/packages/webpack-plugin/lib/platform/template/wx/component-config/scroll-view.js index 19adae3344..1e6e4a2fde 100644 --- a/packages/webpack-plugin/lib/platform/template/wx/component-config/scroll-view.js +++ b/packages/webpack-plugin/lib/platform/template/wx/component-config/scroll-view.js @@ -20,15 +20,6 @@ module.exports = function ({ print }) { return 'mpx-scroll-view' }, props: [ - { - test: /^(scroll-x|scroll-y|scroll-with-animation|enable-flex|enhanced|refresher-enabled|refresher-triggered)$/, - web ({ name, value = 'true' }) { // value is undefined, value is true. eg: - return { - name: `:${name}`, // make props binding - value - } - } - }, { test: /^(enable-flex|scroll-anchorin|refresher-enabled|refresher-threshold|refresher-default-style|refresher-background|refresher-triggered|enhanced|bounces|show-scrollbar|paging-enabled|fast-deceleratio)$/, ali: aliPropLog, diff --git a/packages/webpack-plugin/lib/runtime/components/web/mpx-scroll-view.vue b/packages/webpack-plugin/lib/runtime/components/web/mpx-scroll-view.vue index c22c4d312c..9d4105ab93 100644 --- a/packages/webpack-plugin/lib/runtime/components/web/mpx-scroll-view.vue +++ b/packages/webpack-plugin/lib/runtime/components/web/mpx-scroll-view.vue @@ -260,7 +260,7 @@ if (!id) return id = id.replace(/^(?!#)/, '#') // 没有 # 的 id 补上 #,有 # 的忽略 if (!document.querySelector(id)) return // 不存在元素时阻断,直接调用better-scroll的方法会报错 - this.bs.scrollToElement(id, duration) + this.bs?.scrollToElement(id, duration) }, initLayerComputed () { const wrapper = this.$refs.wrapper From a027fe9862c9bf8e3a6eeb254b12227ef21acc0d Mon Sep 17 00:00:00 2001 From: anotherso1a <1181581742@qq.com> Date: Wed, 6 Sep 2023 16:04:34 +0800 Subject: [PATCH 41/59] style: change id convertor --- .../lib/runtime/components/web/mpx-scroll-view.vue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/webpack-plugin/lib/runtime/components/web/mpx-scroll-view.vue b/packages/webpack-plugin/lib/runtime/components/web/mpx-scroll-view.vue index 9d4105ab93..4bdc171c9d 100644 --- a/packages/webpack-plugin/lib/runtime/components/web/mpx-scroll-view.vue +++ b/packages/webpack-plugin/lib/runtime/components/web/mpx-scroll-view.vue @@ -258,7 +258,7 @@ }, scrollToView (id, duration = 0) { if (!id) return - id = id.replace(/^(?!#)/, '#') // 没有 # 的 id 补上 #,有 # 的忽略 + id = '#' + id if (!document.querySelector(id)) return // 不存在元素时阻断,直接调用better-scroll的方法会报错 this.bs?.scrollToElement(id, duration) }, From 1f159c758d6acdaecfb546905470ec3b7a3b2621 Mon Sep 17 00:00:00 2001 From: xuegan Date: Wed, 6 Sep 2023 16:26:17 +0800 Subject: [PATCH 42/59] =?UTF-8?q?fix:=E4=BF=AE=E5=A4=8Dts-loader-watch-run?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/utils/ts-loader-watch-run-loader-filter.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/webpack-plugin/lib/utils/ts-loader-watch-run-loader-filter.js b/packages/webpack-plugin/lib/utils/ts-loader-watch-run-loader-filter.js index 7da499a3b0..9d147d3d5f 100644 --- a/packages/webpack-plugin/lib/utils/ts-loader-watch-run-loader-filter.js +++ b/packages/webpack-plugin/lib/utils/ts-loader-watch-run-loader-filter.js @@ -1,10 +1,9 @@ module.exports = (loaders, loaderIndex) => { - for (let len = loaders.length; len > 0; --len) { - const currentLoader = loaders[len - 1] + for (let i = loaderIndex; i >= 0; i--) { + const currentLoader = loaders[i] if (currentLoader.path.endsWith('ts-loader/dist/stringify-loader.js')) { - break + return i } - loaderIndex-- } return loaderIndex } From aadee67da063a4955629f0d01b8b9de538f10f8e Mon Sep 17 00:00:00 2001 From: xuegan Date: Wed, 6 Sep 2023 17:19:38 +0800 Subject: [PATCH 43/59] =?UTF-8?q?fix:=E4=BF=AE=E5=A4=8Dsome=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../webpack-plugin/lib/json-compiler/index.js | 57 +++++++++---------- 1 file changed, 26 insertions(+), 31 deletions(-) diff --git a/packages/webpack-plugin/lib/json-compiler/index.js b/packages/webpack-plugin/lib/json-compiler/index.js index f1fb61a53f..93ee1a7ba6 100644 --- a/packages/webpack-plugin/lib/json-compiler/index.js +++ b/packages/webpack-plugin/lib/json-compiler/index.js @@ -56,6 +56,25 @@ module.exports = function (content) { ) } + const fillInComponentPlaceholder = (name, placeholder, placeholderEntry) => { + const componentPlaceholder = json.componentPlaceholder || {} + if (componentPlaceholder[name]) return + componentPlaceholder[name] = placeholder + json.componentPlaceholder = componentPlaceholder + if (placeholderEntry && !json.usingComponents[placeholder]) json.usingComponents[placeholder] = placeholderEntry + } + const normalizePlaceholder = (placeholder) => { + if (typeof placeholder === 'string') { + placeholder = { + name: placeholder + } + } + if (!placeholder.name) { + emitError('The asyncSubpackageRules configuration format of @mpxjs/webpack-plugin a is incorrect') + } + return placeholder + } + const { isUrlRequest, urlToRequest, @@ -195,46 +214,22 @@ module.exports = function (content) { components[name] = entry if (root) { if (placeholder) { - function fillInComponentPlaceholder (placeholderName, resource) { - if (resource) { - // 自定义组件 - if (!json.usingComponents[placeholderName]) { - json.usingComponents[placeholderName] = resource - } - } - if (json.componentPlaceholder) { - if (!json.componentPlaceholder[name]) json.componentPlaceholder[name] = placeholderName - } else { - json.componentPlaceholder = { - [name]: placeholderName - } - } - } - function normalizePlaceholder (placeholder) { - if (typeof placeholder === 'string') { - placeholder = { - name: placeholder - } - } - if (!placeholder.name) { - emitError('The asyncSubpackageRules configuration format of @mpxjs/webpack-plugin a is incorrect') - } - return placeholder - } placeholder = normalizePlaceholder(placeholder) if (placeholder.resource) { processComponent(placeholder.resource, projectRoot, { relativePath }, (err, entry) => { if (err) return callback(err) - fillInComponentPlaceholder(placeholder.name, entry) + fillInComponentPlaceholder(name, placeholder.name, entry) callback() }) } else { - fillInComponentPlaceholder(placeholder.name) + fillInComponentPlaceholder(name, placeholder.name) callback() } - } else if (!json.componentPlaceholder || !json.componentPlaceholder[name]) { - const errMsg = `componentPlaceholder of "${name}" doesn't exist! \n\r` - emitError(errMsg) + } else { + if (!json.componentPlaceholder || !json.componentPlaceholder[name]) { + const errMsg = `componentPlaceholder of "${name}" doesn't exist! \n\r` + emitError(errMsg) + } callback() } } else { From f1066822d83e958f6266218c51c21b2ebb2ad04b Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Thu, 7 Sep 2023 14:29:21 +0800 Subject: [PATCH 44/59] v2.8.43 --- lerna.json | 2 +- packages/webpack-plugin/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lerna.json b/lerna.json index 6806b1c213..6f831da3a9 100644 --- a/lerna.json +++ b/lerna.json @@ -2,5 +2,5 @@ "packages": [ "packages/*" ], - "version": "2.8.42" + "version": "2.8.43" } diff --git a/packages/webpack-plugin/package.json b/packages/webpack-plugin/package.json index 30e69e21b9..fb373539f9 100644 --- a/packages/webpack-plugin/package.json +++ b/packages/webpack-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@mpxjs/webpack-plugin", - "version": "2.8.42", + "version": "2.8.43", "description": "mpx compile core", "keywords": [ "mpx" From 6243f0108cd260153c1aea0d60ec3834e664cf16 Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Tue, 12 Sep 2023 17:19:11 +0800 Subject: [PATCH 45/59] fix web eventChannel --- .../src/web/api/event-channel/index.js | 27 +++++++++---------- .../platform/builtInMixins/pageRouteMixin.js | 7 +++++ .../builtInMixins/proxyEventMixin.web.js | 5 ---- .../lib/runtime/optionProcessor.js | 27 +++++++------------ 4 files changed, 30 insertions(+), 36 deletions(-) diff --git a/packages/api-proxy/src/web/api/event-channel/index.js b/packages/api-proxy/src/web/api/event-channel/index.js index c7e03549f9..23b8c4ad0d 100644 --- a/packages/api-proxy/src/web/api/event-channel/index.js +++ b/packages/api-proxy/src/web/api/event-channel/index.js @@ -19,13 +19,13 @@ class EventChannel { } } - off (eventName, EventCallback) { - if (EventCallback) { + off (eventName, listener) { + if (listener) { const cbs = this.listener[eventName] const copyCbs = [] if (cbs) { cbs.forEach((item) => { - if (item.fn !== EventCallback) { + if (item.fn !== listener) { copyCbs.push(item) } }) @@ -36,26 +36,25 @@ class EventChannel { } } - on (eventName, EventCallback) { - (this.listener[eventName] || (this.listener[eventName] = [])).push({ fn: EventCallback, type: 'on' }) + on (eventName, listener) { + this._addListener(eventName, listener, 'on') } - once (eventName, EventCallback) { - (this.listener[eventName] || (this.listener[eventName] = [])).push({ fn: EventCallback, type: 'once' }) + once (eventName, listener) { + this._addListener(eventName, listener, 'once') } - _addListener (eventName, EventCallback, type) { - (this.listener[eventName] || (this.listener[eventName] = [])).push({ fn: EventCallback, type }) + _addListener (eventName, listener, type) { + (this.listener[eventName] || (this.listener[eventName] = [])).push({ fn: listener, type }) } _addListeners (events) { - if (Object.prototype.toString.call(events) === '[object Object]') { - Object.keys(events).forEach((eventName) => { - (this.listener[eventName] || (this.listener[eventName] = [])).push({ fn: events[eventName], type: 'on' }) - }) - } + Object.keys(events).forEach((eventName) => { + this.on(eventName, events[eventName]) + }) } } + export { EventChannel } diff --git a/packages/core/src/platform/builtInMixins/pageRouteMixin.js b/packages/core/src/platform/builtInMixins/pageRouteMixin.js index 39a0d4ba6a..975f094088 100644 --- a/packages/core/src/platform/builtInMixins/pageRouteMixin.js +++ b/packages/core/src/platform/builtInMixins/pageRouteMixin.js @@ -4,6 +4,13 @@ export default function pageRouteMixin (mixinType) { return { beforeCreate () { this.route = this.$options.__mpxPageRoute || '' + }, + methods: { + getOpenerEventChannel () { + const router = global.__mpxRouter + const eventChannel = router && router.eventChannelMap[this.route] + return eventChannel || {} + } } } } diff --git a/packages/core/src/platform/builtInMixins/proxyEventMixin.web.js b/packages/core/src/platform/builtInMixins/proxyEventMixin.web.js index 9e3d86e0c1..62cd045032 100644 --- a/packages/core/src/platform/builtInMixins/proxyEventMixin.web.js +++ b/packages/core/src/platform/builtInMixins/proxyEventMixin.web.js @@ -18,11 +18,6 @@ export default function proxyEventMixin () { const originValue = valuePath.reduce((acc, cur) => acc[cur], $event.detail) const value = filterMethod ? (innerFilter[filterMethod] ? innerFilter[filterMethod](originValue) : typeof this[filterMethod] === 'function' && this[filterMethod]) : originValue setByPath(this, expr, value) - }, - getOpenerEventChannel () { - const router = global.__mpxRouter - const eventChannel = router && router.__mpxAction && router.__mpxAction.eventChannel - return eventChannel } } } diff --git a/packages/webpack-plugin/lib/runtime/optionProcessor.js b/packages/webpack-plugin/lib/runtime/optionProcessor.js index a20c7a67b5..fb94c196c9 100644 --- a/packages/webpack-plugin/lib/runtime/optionProcessor.js +++ b/packages/webpack-plugin/lib/runtime/optionProcessor.js @@ -59,6 +59,7 @@ export default function processOption ( global.__mpxRouter.stack = [] global.__mpxRouter.needCache = null global.__mpxRouter.needRemove = [] + global.__mpxRouter.eventChannelMap = {} // 处理reLaunch中传递的url并非首页时的replace逻辑 global.__mpxRouter.beforeEach(function (to, from, next) { let action = global.__mpxRouter.__mpxAction @@ -97,24 +98,15 @@ export default function processOption ( }) } } else { - let methods = '' - switch (action.type) { - case 'to': - methods = 'navigateTo' - break - case 'redirect': - methods = 'redirectTo' - break - case 'back': - methods = 'navigateBack' - break - case 'reLaunch': - methods = 'reLaunch' - break - default: - methods = 'navigateTo' + const typeMethodMap = { + to: 'navigateTo', + redirect: 'redirectTo', + back: 'navigateBack', + switch: 'switchTab', + reLaunch: 'reLaunch' } - throw new Error(`${methods}:fail page "${to.path}" is not found`) + const method = typeMethodMap[action.type] + throw new Error(`${method}:fail page "${to.path}" is not found`) } } @@ -126,6 +118,7 @@ export default function processOption ( case 'to': stack.push(insertItem) global.__mpxRouter.needCache = insertItem + if (action.eventChannel) global.__mpxRouter.eventChannelMap[to.path.slice(1)] = action.eventChannel break case 'back': global.__mpxRouter.needRemove = stack.splice(stack.length - action.delta, action.delta) From 7e2c28a765f7d82ecd8988b486672b986771b24f Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Wed, 13 Sep 2023 17:15:55 +0800 Subject: [PATCH 46/59] little adjust --- packages/core/src/platform/builtInMixins/pageRouteMixin.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/core/src/platform/builtInMixins/pageRouteMixin.js b/packages/core/src/platform/builtInMixins/pageRouteMixin.js index 975f094088..1ca7318b21 100644 --- a/packages/core/src/platform/builtInMixins/pageRouteMixin.js +++ b/packages/core/src/platform/builtInMixins/pageRouteMixin.js @@ -14,4 +14,10 @@ export default function pageRouteMixin (mixinType) { } } } + return { + methods: { + getOpenerEventChannel () { + } + } + } } From cd1f38bc84aca8b2a2e5ec890aa1e2f2693f26e3 Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Wed, 13 Sep 2023 17:20:37 +0800 Subject: [PATCH 47/59] v2.8.44 --- lerna.json | 2 +- packages/api-proxy/package.json | 2 +- packages/core/package.json | 2 +- packages/webpack-plugin/package.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lerna.json b/lerna.json index 6f831da3a9..096b74b82c 100644 --- a/lerna.json +++ b/lerna.json @@ -2,5 +2,5 @@ "packages": [ "packages/*" ], - "version": "2.8.43" + "version": "2.8.44" } diff --git a/packages/api-proxy/package.json b/packages/api-proxy/package.json index 0472883ba4..05464b7001 100644 --- a/packages/api-proxy/package.json +++ b/packages/api-proxy/package.json @@ -1,6 +1,6 @@ { "name": "@mpxjs/api-proxy", - "version": "2.8.40", + "version": "2.8.44", "description": "convert miniprogram API at each end", "module": "src/index.js", "types": "@types/index.d.ts", diff --git a/packages/core/package.json b/packages/core/package.json index 58b5fa94f9..414e011e18 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@mpxjs/core", - "version": "2.8.42", + "version": "2.8.44", "description": "mpx runtime core", "keywords": [ "miniprogram", diff --git a/packages/webpack-plugin/package.json b/packages/webpack-plugin/package.json index fb373539f9..7f89d421a9 100644 --- a/packages/webpack-plugin/package.json +++ b/packages/webpack-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@mpxjs/webpack-plugin", - "version": "2.8.43", + "version": "2.8.44", "description": "mpx compile core", "keywords": [ "mpx" From df06baeb434e69f868f30f43a6949ab4a58d2cd9 Mon Sep 17 00:00:00 2001 From: xuegan Date: Thu, 14 Sep 2023 10:55:03 +0800 Subject: [PATCH 48/59] =?UTF-8?q?feat:=E8=B0=83=E6=95=B4size=20report=20pr?= =?UTF-8?q?eWarningSize=20=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/size-report/README.md | 7 +++++-- packages/size-report/src/SizeReportPlugin.js | 6 +++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/packages/size-report/README.md b/packages/size-report/README.md index 5f92bd7c92..90fdcbf31e 100644 --- a/packages/size-report/README.md +++ b/packages/size-report/README.md @@ -64,8 +64,11 @@ const MpxSizeReportPlugin = require('@mpxjs/size-report') }, { name: 'pageGroup', - // 每个分组中可分别配置阈值,如果不配置则表示 - threshold: '500KB', + // 每个分组中可分别配置阈值,如果不配置则表示没任何限制 + threshold: { + size: '500KB', + preWarningSize: true// 可选项,开启分组体积阈值预警,会以warning的形式在每次构建后输出当前分组的剩余体积 + }, entryRules: { include: ['src/pages/index', 'src/pages/user'] } diff --git a/packages/size-report/src/SizeReportPlugin.js b/packages/size-report/src/SizeReportPlugin.js index a09ec553c9..f388f4d215 100644 --- a/packages/size-report/src/SizeReportPlugin.js +++ b/packages/size-report/src/SizeReportPlugin.js @@ -656,15 +656,15 @@ class SizeReportPlugin { function checkThreshold (threshold, size, sizeInfo, reportGroupName) { const sizeThreshold = normalizeThreshold(threshold.size || threshold) - const preWarningThreshold = normalizeThreshold(threshold.preWarningSize || threshold) + const preWarningSize = threshold.preWarningSize const packagesThreshold = threshold.packages const prefix = reportGroupName ? `${reportGroupName}体积分组` : '总包' if (sizeThreshold && size && size > sizeThreshold) { compilation.errors.push(`${prefix}的总体积(${size}B)超过设定阈值(${sizeThreshold}B),共${(size - sizeThreshold) / 1024}kb,请检查!`) } - if (preWarningThreshold && size && size > preWarningThreshold) { - compilation.warnings.push(`${prefix}的总体积(${size}B)超过设定预警阈值(${preWarningThreshold}B),共${(size - preWarningThreshold) / 1024}kb,请注意!`) + if (preWarningSize && size && size < sizeThreshold) { + compilation.warnings.push(`当前${prefix}的总体积 ${size / 1024}kb,${prefix}的体积阈值为${sizeThreshold / 1024}kb, 共剩余${(sizeThreshold - size) / 1024}kb,请注意!`) } if (packagesThreshold && sizeInfo) { From 88716d38a2cf77ffc588b8420e36e5b81383f97e Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Fri, 15 Sep 2023 15:22:08 +0800 Subject: [PATCH 49/59] rm useless files & fix loader match --- packages/webpack-plugin/lib/index.js | 10 +- .../ts-loader-watch-run-loader-filter.js | 2 +- .../lib/wxss/compile-exports.js | 52 ---- .../webpack-plugin/lib/wxss/createResolver.js | 36 --- packages/webpack-plugin/lib/wxss/css-base.js | 79 ----- .../webpack-plugin/lib/wxss/getLocalIdent.js | 25 -- .../webpack-plugin/lib/wxss/localsLoader.js | 44 --- .../webpack-plugin/lib/wxss/processCss.js | 274 ------------------ 8 files changed, 6 insertions(+), 516 deletions(-) delete mode 100644 packages/webpack-plugin/lib/wxss/compile-exports.js delete mode 100644 packages/webpack-plugin/lib/wxss/createResolver.js delete mode 100644 packages/webpack-plugin/lib/wxss/css-base.js delete mode 100644 packages/webpack-plugin/lib/wxss/getLocalIdent.js delete mode 100644 packages/webpack-plugin/lib/wxss/localsLoader.js delete mode 100644 packages/webpack-plugin/lib/wxss/processCss.js diff --git a/packages/webpack-plugin/lib/index.js b/packages/webpack-plugin/lib/index.js index 9d73eea362..132a8d43a9 100644 --- a/packages/webpack-plugin/lib/index.js +++ b/packages/webpack-plugin/lib/index.js @@ -1453,8 +1453,8 @@ try { }) const typeLoaderProcessInfo = { - styles: ['css-loader', wxssLoaderPath, styleCompilerPath], - template: ['html-loader', wxmlLoaderPath, templateCompilerPath] + styles: ['node_modules/css-loader', wxssLoaderPath, styleCompilerPath], + template: ['node_modules/html-loader', wxmlLoaderPath, templateCompilerPath] } // 应用过rules后,注入mpx相关资源编译loader @@ -1517,15 +1517,15 @@ try { if (mpx.mode === 'web') { const mpxStyleOptions = queryObj.mpxStyleOptions const firstLoader = loaders[0] ? toPosix(loaders[0].loader) : '' - const isPitcherRequest = firstLoader.includes('vue-loader/lib/loaders/pitcher') + const isPitcherRequest = firstLoader.includes('node_modules/vue-loader/lib/loaders/pitcher') let cssLoaderIndex = -1 let vueStyleLoaderIndex = -1 let mpxStyleLoaderIndex = -1 loaders.forEach((loader, index) => { const currentLoader = toPosix(loader.loader) - if (currentLoader.includes('css-loader') && cssLoaderIndex === -1) { + if (currentLoader.includes('node_modules/css-loader') && cssLoaderIndex === -1) { cssLoaderIndex = index - } else if (currentLoader.includes('vue-loader/lib/loaders/stylePostLoader') && vueStyleLoaderIndex === -1) { + } else if (currentLoader.includes('node_modules/vue-loader/lib/loaders/stylePostLoader') && vueStyleLoaderIndex === -1) { vueStyleLoaderIndex = index } else if (currentLoader.includes(styleCompilerPath) && mpxStyleLoaderIndex === -1) { mpxStyleLoaderIndex = index diff --git a/packages/webpack-plugin/lib/utils/ts-loader-watch-run-loader-filter.js b/packages/webpack-plugin/lib/utils/ts-loader-watch-run-loader-filter.js index 9d147d3d5f..eb93027bc4 100644 --- a/packages/webpack-plugin/lib/utils/ts-loader-watch-run-loader-filter.js +++ b/packages/webpack-plugin/lib/utils/ts-loader-watch-run-loader-filter.js @@ -1,7 +1,7 @@ module.exports = (loaders, loaderIndex) => { for (let i = loaderIndex; i >= 0; i--) { const currentLoader = loaders[i] - if (currentLoader.path.endsWith('ts-loader/dist/stringify-loader.js')) { + if (currentLoader.path.endsWith('node_modules/ts-loader/dist/stringify-loader.js')) { return i } } diff --git a/packages/webpack-plugin/lib/wxss/compile-exports.js b/packages/webpack-plugin/lib/wxss/compile-exports.js deleted file mode 100644 index 749d229f3a..0000000000 --- a/packages/webpack-plugin/lib/wxss/compile-exports.js +++ /dev/null @@ -1,52 +0,0 @@ -const camelCase = require('lodash.camelcase') - -function dashesCamelCase (str) { - return str.replace(/-+(\w)/g, function (match, firstLetter) { - return firstLetter.toUpperCase() - }) -} - -module.exports = function compileExports (result, importItemMatcher, camelCaseKeys) { - if (!Object.keys(result.exports).length) { - return '' - } - - const exportJs = Object.keys(result.exports).reduce(function (res, key) { - let valueAsString = JSON.stringify(result.exports[key]) - valueAsString = valueAsString.replace(result.importItemRegExpG, importItemMatcher) - - function addEntry (k) { - res.push('\t' + JSON.stringify(k) + ': ' + valueAsString) - } - - let targetKey - switch (camelCaseKeys) { - case true: - addEntry(key) - targetKey = camelCase(key) - if (targetKey !== key) { - addEntry(targetKey) - } - break - case 'dashes': - addEntry(key) - targetKey = dashesCamelCase(key) - if (targetKey !== key) { - addEntry(targetKey) - } - break - case 'only': - addEntry(camelCase(key)) - break - case 'dashesOnly': - addEntry(dashesCamelCase(key)) - break - default: - addEntry(key) - break - } - return res - }, []).join(',\n') - - return '{\n' + exportJs + '\n}' -} diff --git a/packages/webpack-plugin/lib/wxss/createResolver.js b/packages/webpack-plugin/lib/wxss/createResolver.js deleted file mode 100644 index dbeb7fa052..0000000000 --- a/packages/webpack-plugin/lib/wxss/createResolver.js +++ /dev/null @@ -1,36 +0,0 @@ -module.exports = function createResolver (alias) { - if (typeof alias !== 'object' || Array.isArray(alias)) { - return function (url) { - return url - } - } - - alias = Object.keys(alias).map(function (key) { - let onlyModule = false - let obj = alias[key] - if (/\$$/.test(key)) { - onlyModule = true - key = key.substr(0, key.length - 1) - } - if (typeof obj === 'string') { - obj = { - alias: obj - } - } - obj = Object.assign({ - name: key, - onlyModule: onlyModule - }, obj) - return obj - }) - - return function (url) { - alias.forEach(function (obj) { - const name = obj.name - if (url === name || (!obj.onlyModule && url.startsWith(name + '/'))) { - url = obj.alias + url.substr(name.length) - } - }) - return url - } -} diff --git a/packages/webpack-plugin/lib/wxss/css-base.js b/packages/webpack-plugin/lib/wxss/css-base.js deleted file mode 100644 index 1fe3e40c12..0000000000 --- a/packages/webpack-plugin/lib/wxss/css-base.js +++ /dev/null @@ -1,79 +0,0 @@ -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - Modified by @hiyuki -*/ -// css base code, injected by the css-loader -module.exports = function (useSourceMap) { - const list = [] - - // return the list of modules as css string - list.toString = function toString () { - return this.map(function (item) { - const content = cssWithMappingToString(item, useSourceMap) - if (item[2]) { - return '@media ' + item[2] + '{' + content + '}' - } else { - return content - } - }).join('') - } - - // import a list of modules into the list - list.i = function (modules, mediaQuery) { - if (typeof modules === 'string') { - modules = [[null, modules, '']] - } - const alreadyImportedModules = {} - for (let i = 0; i < this.length; i++) { - const id = this[i][0] - if (typeof id === 'number') { - alreadyImportedModules[id] = true - } - } - for (let i = 0; i < modules.length; i++) { - const item = modules[i] - // skip already imported module - // this implementation is not 100% perfect for weird media query combinations - // when a module is imported multiple times with different media queries. - // I hope this will never occur (Hey this way we have smaller bundles) - if (typeof item[0] !== 'number' || !alreadyImportedModules[item[0]]) { - if (mediaQuery && !item[2]) { - item[2] = mediaQuery - } else if (mediaQuery) { - item[2] = '(' + item[2] + ') and (' + mediaQuery + ')' - } - list.push(item) - } - } - } - return list -} - -function cssWithMappingToString (item, useSourceMap) { - const content = item[1] || '' - const cssMapping = item[3] - if (!cssMapping) { - return content - } - - if (useSourceMap && typeof btoa === 'function') { - const sourceMapping = toComment(cssMapping) - const sourceURLs = cssMapping.sources.map(function (source) { - return '/*# sourceURL=' + cssMapping.sourceRoot + source + ' */' - }) - - return [content].concat(sourceURLs).concat([sourceMapping]).join('\n') - } - - return [content].join('\n') -} - -// Adapted from convert-source-map (MIT) -function toComment (sourceMap) { - // eslint-disable-next-line no-undef - const base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) - const data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64 - - return '/*# ' + data + ' */' -} diff --git a/packages/webpack-plugin/lib/wxss/getLocalIdent.js b/packages/webpack-plugin/lib/wxss/getLocalIdent.js deleted file mode 100644 index e3d07e7d6f..0000000000 --- a/packages/webpack-plugin/lib/wxss/getLocalIdent.js +++ /dev/null @@ -1,25 +0,0 @@ -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - Modified by @hiyuki -*/ -const loaderUtils = require('loader-utils') -const path = require('path') - -module.exports = function getLocalIdent (loaderContext, localIdentName, localName, options) { - if (!options.context) { - if (loaderContext.rootContext) { - options.context = loaderContext.rootContext - } else if (loaderContext.options && typeof loaderContext.options.context === 'string') { - options.context = loaderContext.options.context - } else { - options.context = loaderContext.context - } - } - const request = path.relative(options.context, loaderContext.resourcePath) - options.content = options.hashPrefix + request + '+' + localName - localIdentName = localIdentName.replace(/\[local\]/gi, localName) - const hash = loaderUtils.interpolateName(loaderContext, localIdentName, options) - /* eslint-disable prefer-regex-literals */ - return hash.replace(new RegExp('[^a-zA-Z0-9\\-_\u00A0-\uFFFF]', 'g'), '-').replace(/^((-?[0-9])|--)/, '_$1') -} diff --git a/packages/webpack-plugin/lib/wxss/localsLoader.js b/packages/webpack-plugin/lib/wxss/localsLoader.js deleted file mode 100644 index 802199a198..0000000000 --- a/packages/webpack-plugin/lib/wxss/localsLoader.js +++ /dev/null @@ -1,44 +0,0 @@ -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - Modified by @hiyuki -*/ -const loaderUtils = require('loader-utils') -const processCss = require('./processCss') -const compileExports = require('./compile-exports') -const createResolver = require('./createResolver') - -module.exports = function (content) { - if (this.cacheable) this.cacheable() - const callback = this.async() - const query = loaderUtils.getOptions(this) || {} - const moduleMode = query.modules || query.module - const camelCaseKeys = query.camelCase || query.camelcase - const resolve = createResolver(query.alias) - - processCss(content, null, { - mode: moduleMode ? 'local' : 'global', - query: query, - minimize: this.minimize, - loaderContext: this, - resolve: resolve - }, function (err, result) { - if (err) return callback(err) - - function importItemMatcher (item) { - const match = result.importItemRegExp.exec(item) - const idx = +match[1] - const importItem = result.importItems[idx] - const importUrl = importItem.url - return '" + require(' + loaderUtils.stringifyRequest(this, importUrl) + ')' + - '[' + JSON.stringify(importItem.export) + '] + "' - } - - let exportJs = compileExports(result, importItemMatcher.bind(this), camelCaseKeys) - if (exportJs) { - exportJs = 'module.exports = ' + exportJs + ';' - } - - callback(null, exportJs) - }.bind(this)) -} diff --git a/packages/webpack-plugin/lib/wxss/processCss.js b/packages/webpack-plugin/lib/wxss/processCss.js deleted file mode 100644 index 85d0257cd9..0000000000 --- a/packages/webpack-plugin/lib/wxss/processCss.js +++ /dev/null @@ -1,274 +0,0 @@ -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - Modified by @hiyuki -*/ -const formatCodeFrame = require('@babel/code-frame') -const Tokenizer = require('css-selector-tokenizer') -const postcss = require('postcss') -const loaderUtils = require('loader-utils') -const assign = require('object-assign') -const getLocalIdent = require('./getLocalIdent') - -const icssUtils = require('icss-utils') -const localByDefault = require('postcss-modules-local-by-default') -const extractImports = require('postcss-modules-extract-imports') -const modulesScope = require('postcss-modules-scope') -const modulesValues = require('postcss-modules-values') -const valueParser = require('postcss-value-parser') -const isUrlRequest = require('../utils/is-url-request') -// css-loader-parser - -const parserPlugin = function (options) { - return { - postcssPlugin: 'css-loader-parser', - Once (css) { - const imports = {} - let exports = {} - const importItems = [] - const urlItems = [] - - function replaceImportsInString (str) { - if (options.import) { - const tokens = valueParser(str) - tokens.walk(function (node) { - if (node.type !== 'word') { - return - } - const token = node.value - const importIndex = imports['$' + token] - if (typeof importIndex === 'number') { - node.value = '___CSS_LOADER_IMPORT___' + importIndex + '___' - } - }) - return tokens.toString() - } - return str - } - - if (options.import) { - css.walkAtRules(/^import$/i, function (rule) { - const values = Tokenizer.parseValues(rule.params) - let url = values.nodes[0].nodes[0] - if (url && url.type === 'url') { - url = url.url - } else if (url && url.type === 'string') { - url = url.value - } else throw rule.error('Unexpected format ' + rule.params) - if (!url.replace(/\s/g, '').length) { - return - } - values.nodes[0].nodes.shift() - const mediaQuery = Tokenizer.stringifyValues(values) - - if (isUrlRequest(url, options.root)) { - url = loaderUtils.urlToRequest(url, options.root) - } - - importItems.push({ - url: url, - mediaQuery: mediaQuery - }) - rule.remove() - }) - } - - const icss = icssUtils.extractICSS(css) - exports = icss.icssExports - Object.keys(icss.icssImports).forEach(function (key) { - const url = loaderUtils.parseString(key) - Object.keys(icss.icssImports[key]).forEach(function (prop) { - imports['$' + prop] = importItems.length - importItems.push({ - url: url, - export: icss.icssImports[key][prop] - }) - }) - }) - - Object.keys(exports).forEach(function (exportName) { - exports[exportName] = replaceImportsInString(exports[exportName]) - }) - - function isAlias (url) { - // Handle alias starting by / and root disabled - return url !== options.resolve(url) - } - - function processNode (item) { - switch (item.type) { - case 'value': - item.nodes.forEach(processNode) - break - case 'nested-item': - item.nodes.forEach(processNode) - break - case 'item': { - const importIndex = imports['$' + item.name] - if (typeof importIndex === 'number') { - item.name = '___CSS_LOADER_IMPORT___' + importIndex + '___' - } - break - } - case 'url': - if (options.url && item.url.replace(/\s/g, '').length && !/^#/.test(item.url) && (isAlias(item.url) || isUrlRequest(item.url, options.root))) { - // Strip quotes, they will be re-added if the module needs them - item.stringType = '' - delete item.innerSpacingBefore - delete item.innerSpacingAfter - const url = item.url - item.url = '___CSS_LOADER_URL___' + urlItems.length + '___' - urlItems.push({ - url: url - }) - } - break - } - } - - css.walkDecls(function (decl) { - const values = Tokenizer.parseValues(decl.value) - values.nodes.forEach(function (value) { - value.nodes.forEach(processNode) - }) - decl.value = Tokenizer.stringifyValues(values) - }) - css.walkAtRules(function (atrule) { - if (typeof atrule.params === 'string') { - atrule.params = replaceImportsInString(atrule.params) - } - }) - - options.importItems = importItems - options.urlItems = urlItems - options.exports = exports - } - } -} - -module.exports = function processCss (inputSource, inputMap, options, callback) { - const query = options.query - const root = query.root && query.root.length > 0 ? query.root.replace(/\/$/, '') : query.root - const context = query.context - const localIdentName = query.localIdentName || '[hash:base64]' - const localIdentRegExp = query.localIdentRegExp - const forceMinimize = query.minimize - const minimize = typeof forceMinimize !== 'undefined' ? !!forceMinimize : options.minimize - - const customGetLocalIdent = query.getLocalIdent || getLocalIdent - - const parserOptions = { - root: root, - mode: options.mode, - url: query.url !== false, - import: query.import !== false, - resolve: options.resolve - } - - const pipeline = postcss([ - modulesValues, - localByDefault({ - mode: options.mode, - rewriteUrl: function (global, url) { - if (parserOptions.url) { - url = url.trim() - - if (!url.replace(/\s/g, '').length || !isUrlRequest(url, root)) { - return url - } - if (global) { - return loaderUtils.urlToRequest(url, root) - } - } - return url - } - }), - extractImports(), - modulesScope({ - generateScopedName: function generateScopedName (exportName) { - return customGetLocalIdent(options.loaderContext, localIdentName, exportName, { - regExp: localIdentRegExp, - hashPrefix: query.hashPrefix || '', - context: context - }) - } - }), - parserPlugin(parserOptions) - ]) - - if (minimize) { - const cssnano = require('cssnano') - const minimizeOptions = assign({}, query.minimize); - ['zindex', 'normalizeUrl', 'discardUnused', 'mergeIdents', 'reduceIdents', 'autoprefixer', 'svgo'].forEach(function (name) { - if (typeof minimizeOptions[name] === 'undefined') { - minimizeOptions[name] = false - } - }) - pipeline.use(cssnano(minimizeOptions)) - } - - pipeline.process(inputSource, { - // we need a prefix to avoid path rewriting of PostCSS - from: '/css-loader!' + options.from, - to: options.to, - map: options.sourceMap - ? { - prev: inputMap, - sourcesContent: true, - inline: false, - annotation: false - } - : null - }).then(function (result) { - callback(null, { - source: result.css, - map: result.map && result.map.toJSON(), - exports: parserOptions.exports, - importItems: parserOptions.importItems, - importItemRegExpG: /___CSS_LOADER_IMPORT___([0-9]+)___/g, - importItemRegExp: /___CSS_LOADER_IMPORT___([0-9]+)___/, - urlItems: parserOptions.urlItems, - urlItemRegExpG: /___CSS_LOADER_URL___([0-9]+)___/g, - urlItemRegExp: /___CSS_LOADER_URL___([0-9]+)___/ - }) - }).catch(function (err) { - if (err.name === 'CssSyntaxError') { - const wrappedError = new CSSLoaderError( - 'Syntax Error', - err.reason, - err.line != null && err.column != null - ? { line: err.line, column: err.column } - : null, - err.input.source - ) - callback(wrappedError) - } else { - callback(err) - } - }) -} - -function formatMessage (message, loc, source) { - let formatted = message - if (loc) { - formatted = formatted + - ' (' + loc.line + ':' + loc.column + ')' - } - if (loc && source) { - formatted = formatted + - '\n\n' + formatCodeFrame(source, loc.line, loc.column) + '\n' - } - return formatted -} - -function CSSLoaderError (name, message, loc, source, error) { - Error.call(this) - Error.captureStackTrace(this, CSSLoaderError) - this.name = name - this.error = error - this.message = formatMessage(message, loc, source) - this.message = formatMessage(message, loc, source) -} - -CSSLoaderError.prototype = Object.create(Error.prototype) -CSSLoaderError.prototype.constructor = CSSLoaderError From b60613d3d5bfd85c7c7b28b81afbf4494c8b2c6f Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Fri, 15 Sep 2023 15:37:15 +0800 Subject: [PATCH 50/59] v2.8.45 --- lerna.json | 2 +- packages/webpack-plugin/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lerna.json b/lerna.json index 096b74b82c..3b3c0d5681 100644 --- a/lerna.json +++ b/lerna.json @@ -2,5 +2,5 @@ "packages": [ "packages/*" ], - "version": "2.8.44" + "version": "2.8.45" } diff --git a/packages/webpack-plugin/package.json b/packages/webpack-plugin/package.json index 7f89d421a9..b7cb0cdee6 100644 --- a/packages/webpack-plugin/package.json +++ b/packages/webpack-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@mpxjs/webpack-plugin", - "version": "2.8.44", + "version": "2.8.45", "description": "mpx compile core", "keywords": [ "mpx" From 394d83b356612b89d2324d20530878f8a7510213 Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Mon, 18 Sep 2023 14:49:20 +0800 Subject: [PATCH 51/59] fix event platform rules --- .../lib/platform/template/wx/index.js | 51 ++++++++++++++++--- 1 file changed, 45 insertions(+), 6 deletions(-) diff --git a/packages/webpack-plugin/lib/platform/template/wx/index.js b/packages/webpack-plugin/lib/platform/template/wx/index.js index 4d5ba8f5a8..223f086b95 100644 --- a/packages/webpack-plugin/lib/platform/template/wx/index.js +++ b/packages/webpack-plugin/lib/platform/template/wx/index.js @@ -195,7 +195,7 @@ module.exports = function getSpec ({ warn, error }) { const parsed = parseMustache(item.value) if (item.name === 'wx:style') { styleBinding.push(parsed.result) - // item.name === 'style' + // item.name === 'style' } else if (parsed.hasBinding || parsed.result.indexOf('rpx') > -1) { styleBinding.push(parsed.result) } else { @@ -295,18 +295,39 @@ module.exports = function getSpec ({ warn, error }) { }, swan ({ name, value }, { eventRules }) { const match = this.test.exec(name) + const prefix = match[1] const eventName = match[2] - runRules(eventRules, eventName, { mode: 'swan' }) + const modifierStr = match[3] || '' + const rPrefix = runRules(spec.event.prefix, prefix, { mode: 'swan' }) + const rEventName = runRules(eventRules, eventName, { mode: 'swan' }) + return { + name: rPrefix + rEventName + modifierStr, + value + } }, qq ({ name, value }, { eventRules }) { const match = this.test.exec(name) + const prefix = match[1] const eventName = match[2] - runRules(eventRules, eventName, { mode: 'qq' }) + const modifierStr = match[3] || '' + const rPrefix = runRules(spec.event.prefix, prefix, { mode: 'qq' }) + const rEventName = runRules(eventRules, eventName, { mode: 'qq' }) + return { + name: rPrefix + rEventName + modifierStr, + value + } }, jd ({ name, value }, { eventRules }) { const match = this.test.exec(name) + const prefix = match[1] const eventName = match[2] - runRules(eventRules, eventName, { mode: 'jd' }) + const modifierStr = match[3] || '' + const rPrefix = runRules(spec.event.prefix, prefix, { mode: 'jd' }) + const rEventName = runRules(eventRules, eventName, { mode: 'jd' }) + return { + name: rPrefix + rEventName + modifierStr, + value + } }, // tt ({ name, value }, { eventRules }) { // const match = this.test.exec(name) @@ -322,15 +343,33 @@ module.exports = function getSpec ({ warn, error }) { // }, tt ({ name, value }, { eventRules }) { const match = this.test.exec(name) + const prefix = match[1] const eventName = match[2] - runRules(eventRules, eventName, { mode: 'tt' }) + const modifierStr = match[3] || '' + const rPrefix = runRules(spec.event.prefix, prefix, { mode: 'tt' }) + const rEventName = runRules(eventRules, eventName, { mode: 'tt' }) + return { + name: rPrefix + rEventName + modifierStr, + value + } }, dd ({ name, value }, { eventRules }) { const match = this.test.exec(name) + const prefix = match[1] const eventName = match[2] - runRules(eventRules, eventName, { mode: 'dd' }) + const modifierStr = match[3] || '' + const rPrefix = runRules(spec.event.prefix, prefix, { mode: 'dd' }) + const rEventName = runRules(eventRules, eventName, { mode: 'dd' }) + return { + name: rPrefix + rEventName + modifierStr, + value + } }, web ({ name, value }, { eventRules, el }) { + if (parseMustache(value).hasBinding) { + error('Web environment does not support mustache binding in event props!') + return + } const match = this.test.exec(name) const prefix = match[1] const eventName = match[2] From bd736c9138e8b8abe194c2603cc6b20a224390dc Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Mon, 18 Sep 2023 17:59:32 +0800 Subject: [PATCH 52/59] fix web route for A->A or A->B->A --- packages/api-proxy/src/web/api/route/index.js | 30 ++++++++++++------- .../runtime/components/web/mpx-keep-alive.vue | 25 +++++----------- .../lib/runtime/optionProcessor.js | 2 +- 3 files changed, 29 insertions(+), 28 deletions(-) diff --git a/packages/api-proxy/src/web/api/route/index.js b/packages/api-proxy/src/web/api/route/index.js index 58c256592d..3410d67347 100644 --- a/packages/api-proxy/src/web/api/route/index.js +++ b/packages/api-proxy/src/web/api/route/index.js @@ -1,6 +1,8 @@ import { webHandleSuccess, webHandleFail, isTabBarPage } from '../../../common/js' import { EventChannel } from '../event-channel' +let routeCount = 0 + function redirectTo (options = {}) { const router = global.__mpxRouter if (router) { @@ -9,11 +11,17 @@ function redirectTo (options = {}) { webHandleFail(res, options.fail, options.complete) return Promise.reject(res) } - router.__mpxAction = { type: 'redirect' } + router.__mpxAction = { + type: 'redirect' + } + if (routeCount === 0 && router.currentRoute.query.routeCount) routeCount = router.currentRoute.query.routeCount return new Promise((resolve, reject) => { router.replace( { - path: options.url + path: options.url, + query: { + routeCount: ++routeCount + } }, () => { const res = { errMsg: 'redirectTo:ok' } @@ -46,10 +54,14 @@ function navigateTo (options = {}) { if (options.events) { eventChannel._addListeners(options.events) } + if (routeCount === 0 && router.currentRoute.query.routeCount) routeCount = router.currentRoute.query.routeCount return new Promise((resolve, reject) => { router.push( { - path: options.url + path: options.url, + query: { + routeCount: ++routeCount + } }, () => { const res = { errMsg: 'navigateTo:ok', eventChannel } @@ -81,19 +93,17 @@ function navigateBack (options = {}) { } } -let reLaunchCount = 0 - function reLaunch (options = {}) { const router = global.__mpxRouter if (router) { - if (reLaunchCount === 0 && router.currentRoute.query.reLaunchCount) reLaunchCount = router.currentRoute.query.reLaunchCount - const delta = router.stack.length - 1 + if (routeCount === 0 && router.currentRoute.query.routeCount) routeCount = router.currentRoute.query.routeCount router.__mpxAction = { type: 'reLaunch', path: options.url, - reLaunchCount: ++reLaunchCount, + routeCount: ++routeCount, replaced: false } + const delta = router.stack.length - 1 // 在需要操作后退时,先操作后退,在beforeEach中基于当前action通过next()进行replace操作,避免部分浏览器的表现不一致 if (delta > 0) { router.go(-delta) @@ -104,7 +114,7 @@ function reLaunch (options = {}) { { path: options.url, query: { - reLaunchCount + routeCount } }, () => { @@ -137,12 +147,12 @@ function switchTab (options = {}) { webHandleFail(res, options.fail, options.complete) return Promise.reject(res) } - const delta = router.stack.length - 1 router.__mpxAction = { type: 'switch', path: options.url, replaced: false } + const delta = router.stack.length - 1 if (delta > 0) { router.go(-delta) } else { diff --git a/packages/webpack-plugin/lib/runtime/components/web/mpx-keep-alive.vue b/packages/webpack-plugin/lib/runtime/components/web/mpx-keep-alive.vue index fcd5a475d9..3fc40eceb5 100644 --- a/packages/webpack-plugin/lib/runtime/components/web/mpx-keep-alive.vue +++ b/packages/webpack-plugin/lib/runtime/components/web/mpx-keep-alive.vue @@ -30,9 +30,7 @@ } function getVnodeKey (vnode) { - if (vnode && vnode.componentOptions) { - return vnode.componentOptions.Ctor.cid + (vnode.componentOptions.tag ? ('::' + (vnode.componentOptions.tag)) : '') - } + return vnode.tag + (vnode.key ? `::${vnode.key}` : '') } export default { @@ -44,12 +42,13 @@ if (!isBrowser) { return vnode || (slot && slot[0]) } - const vnodeKey = getVnodeKey(vnode) const router = global.__mpxRouter - if (vnodeKey && router && vnode.data.routerView) { + if (router) { + // 存在routeCount的情况下修改vnode.key避免patch时复用旧节点实例 + if (router.currentRoute.query.routeCount) vnode.key = router.currentRoute.query.routeCount + const vnodeKey = getVnodeKey(vnode) if (router.needCache) { router.needCache.vnode = vnode - router.needCache.vnodeKey = vnodeKey router.needCache = null } @@ -69,25 +68,17 @@ const stack = router.stack if (stack.length) { - // 只要历史栈缓存中存在对应的页面存活实例,就进行复用 + // 只要历史栈缓存中存在对应的页面存活实例且vnodeKey相同,就进行复用 for (let i = stack.length; i > 0; i--) { const current = stack[i - 1] - if (current.vnode && current.vnodeKey === vnodeKey && current.vnode.componentInstance) { + if (current.vnode && getVnodeKey(current.vnode) === vnodeKey && current.vnode.componentInstance) { vnode.componentInstance = current.vnode.componentInstance - // 避免组件实例复用但是vnode.key不一致带来的bad case - vnode.key = current.vnode.key break } } } - if (router.__mpxAction) { - if (router.__mpxAction.type === 'reLaunch') { - // reLaunch时修改新vnode的key, 确保任何情况下都新创建组件实例 - vnode.key = (vnode.key || '') + router.__mpxAction.reLaunchCount - } - router.__mpxAction = null - } + if (router.__mpxAction) router.__mpxAction = null vnode.data.keepAlive = true } diff --git a/packages/webpack-plugin/lib/runtime/optionProcessor.js b/packages/webpack-plugin/lib/runtime/optionProcessor.js index fb94c196c9..725bc370c5 100644 --- a/packages/webpack-plugin/lib/runtime/optionProcessor.js +++ b/packages/webpack-plugin/lib/runtime/optionProcessor.js @@ -159,7 +159,7 @@ export default function processOption ( return next({ path: action.path, query: { - reLaunchCount: action.reLaunchCount + routeCount: action.routeCount }, replace: true }) From dcf6f000660d56207ff414cb776e8bc6d5ce651f Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Mon, 18 Sep 2023 19:34:25 +0800 Subject: [PATCH 53/59] v2.8.46 --- lerna.json | 2 +- packages/api-proxy/package.json | 2 +- packages/webpack-plugin/package.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lerna.json b/lerna.json index 3b3c0d5681..ede9d50d47 100644 --- a/lerna.json +++ b/lerna.json @@ -2,5 +2,5 @@ "packages": [ "packages/*" ], - "version": "2.8.45" + "version": "2.8.46" } diff --git a/packages/api-proxy/package.json b/packages/api-proxy/package.json index 05464b7001..810a9b157b 100644 --- a/packages/api-proxy/package.json +++ b/packages/api-proxy/package.json @@ -1,6 +1,6 @@ { "name": "@mpxjs/api-proxy", - "version": "2.8.44", + "version": "2.8.46", "description": "convert miniprogram API at each end", "module": "src/index.js", "types": "@types/index.d.ts", diff --git a/packages/webpack-plugin/package.json b/packages/webpack-plugin/package.json index b7cb0cdee6..e3044976ad 100644 --- a/packages/webpack-plugin/package.json +++ b/packages/webpack-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@mpxjs/webpack-plugin", - "version": "2.8.45", + "version": "2.8.46", "description": "mpx compile core", "keywords": [ "mpx" From bacc290001575206bcd9c5a55db7a7176111e5ac Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Tue, 19 Sep 2023 18:54:59 +0800 Subject: [PATCH 54/59] =?UTF-8?q?=E8=BE=93=E5=87=BAweb=E6=97=B6=E5=A4=84?= =?UTF-8?q?=E7=90=86=E8=BD=AC=E4=B9=89=E5=BC=95=E5=8F=B7=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/platform/template/wx/index.js | 9 +-------- .../lib/template-compiler/compiler.js | 13 +++++++------ 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/packages/webpack-plugin/lib/platform/template/wx/index.js b/packages/webpack-plugin/lib/platform/template/wx/index.js index 223f086b95..46281db0d8 100644 --- a/packages/webpack-plugin/lib/platform/template/wx/index.js +++ b/packages/webpack-plugin/lib/platform/template/wx/index.js @@ -193,14 +193,7 @@ module.exports = function getSpec ({ warn, error }) { // 不过滤的话每一个属性都要 parse el.attrsList.filter(item => this.test.test(item.name)).forEach((item) => { const parsed = parseMustache(item.value) - if (item.name === 'wx:style') { - styleBinding.push(parsed.result) - // item.name === 'style' - } else if (parsed.hasBinding || parsed.result.indexOf('rpx') > -1) { - styleBinding.push(parsed.result) - } else { - styleBinding.push(JSON.stringify(item.value)) - } + styleBinding.push(parsed.result) }) return { name: ':style', diff --git a/packages/webpack-plugin/lib/template-compiler/compiler.js b/packages/webpack-plugin/lib/template-compiler/compiler.js index 33379f1490..eb24a0bac4 100644 --- a/packages/webpack-plugin/lib/template-compiler/compiler.js +++ b/packages/webpack-plugin/lib/template-compiler/compiler.js @@ -878,6 +878,7 @@ function moveBaseDirective (target, from, isDelete = true) { } function stringify (str) { + if (mode === 'web') str = str.replace(/'/g, '"') return JSON.stringify(str) } @@ -988,7 +989,7 @@ function parseFuncStr2 (str) { if (subIndex) { const index1 = ret.index + subIndex const index2 = index1 + 6 - args = args.substring(0, index1) + JSON.stringify(eventIdentifier) + args.substring(index2) + args = args.substring(0, index1) + stringify(eventIdentifier) + args.substring(index2) } } return { @@ -1016,7 +1017,7 @@ function stringifyWithResolveComputed (modelValue) { computedStack.push(char) if (computedStack.length === 1) { fragment += '.' - result.push(JSON.stringify(fragment)) + result.push(stringify(fragment)) fragment = '' continue } @@ -1033,7 +1034,7 @@ function stringifyWithResolveComputed (modelValue) { fragment += char } if (fragment !== '') { - result.push(JSON.stringify(fragment)) + result.push(stringify(fragment)) } return result.join('+') } @@ -1696,7 +1697,7 @@ function processWebExternalClassesHack (el, options) { options.externalClasses.forEach((className) => { const index = classNames.indexOf(className) if (index > -1) { - replacements.push(`$attrs[${JSON.stringify(className)}]`) + replacements.push(`$attrs[${stringify(className)}]`) classNames.splice(index, 1) } }) @@ -1730,13 +1731,13 @@ function processWebExternalClassesHack (el, options) { options.externalClasses.forEach((className) => { const index = classNames.indexOf(className) if (index > -1) { - replacements.push(`$attrs[${JSON.stringify(className)}]`) + replacements.push(`$attrs[${stringify(className)}]`) classNames.splice(index, 1) } }) if (classNames.length) { - replacements.unshift(JSON.stringify(classNames.join(' '))) + replacements.unshift(stringify(classNames.join(' '))) } addAttrs(el, [{ From 0f4d4d2a0739549f45cf178f2df7740ff36a6438 Mon Sep 17 00:00:00 2001 From: anotherso1a <1181581742@qq.com> Date: Wed, 20 Sep 2023 11:22:45 +0800 Subject: [PATCH 55/59] fix(web): fix refs regexp When using underscores as the value of refs prop, it will be lost during web runtime --- packages/core/src/platform/builtInMixins/refsMixin.web.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/src/platform/builtInMixins/refsMixin.web.js b/packages/core/src/platform/builtInMixins/refsMixin.web.js index 05b56bc780..d09722168b 100644 --- a/packages/core/src/platform/builtInMixins/refsMixin.web.js +++ b/packages/core/src/platform/builtInMixins/refsMixin.web.js @@ -8,7 +8,7 @@ function getEl (ref) { function processRefs (refs) { Object.keys(refs).forEach((key) => { - const matched = /^__mpx_ref_([^_]+)__$/.exec(key) + const matched = /^__mpx_ref_(.+)__$/.exec(key) const rKey = matched && matched[1] if (rKey) { const ref = refs[key] From 9069d7f3931841a7e3acaf990464813a3b6ccb0c Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Wed, 20 Sep 2023 15:13:16 +0800 Subject: [PATCH 56/59] v2.8.47 --- lerna.json | 2 +- packages/core/package.json | 2 +- packages/size-report/package.json | 2 +- packages/webpack-plugin/package.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lerna.json b/lerna.json index ede9d50d47..ba3b04c822 100644 --- a/lerna.json +++ b/lerna.json @@ -2,5 +2,5 @@ "packages": [ "packages/*" ], - "version": "2.8.46" + "version": "2.8.47" } diff --git a/packages/core/package.json b/packages/core/package.json index 414e011e18..fab2d08d11 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@mpxjs/core", - "version": "2.8.44", + "version": "2.8.47", "description": "mpx runtime core", "keywords": [ "miniprogram", diff --git a/packages/size-report/package.json b/packages/size-report/package.json index 507021d257..77c6485096 100644 --- a/packages/size-report/package.json +++ b/packages/size-report/package.json @@ -1,6 +1,6 @@ { "name": "@mpxjs/size-report", - "version": "2.8.42", + "version": "2.8.47", "description": "mpx size report plugin", "main": "src/index.js", "scripts": { diff --git a/packages/webpack-plugin/package.json b/packages/webpack-plugin/package.json index e3044976ad..fe6dd130e8 100644 --- a/packages/webpack-plugin/package.json +++ b/packages/webpack-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@mpxjs/webpack-plugin", - "version": "2.8.46", + "version": "2.8.47", "description": "mpx compile core", "keywords": [ "mpx" From 001c93672dc1630e4c0fad6a85ebe7d6ef2e3ed3 Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Wed, 20 Sep 2023 16:04:24 +0800 Subject: [PATCH 57/59] compute webpackTemplateSize --- packages/size-report/src/SizeReportPlugin.js | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/packages/size-report/src/SizeReportPlugin.js b/packages/size-report/src/SizeReportPlugin.js index f388f4d215..4bb7ab735e 100644 --- a/packages/size-report/src/SizeReportPlugin.js +++ b/packages/size-report/src/SizeReportPlugin.js @@ -132,7 +132,11 @@ class SizeReportPlugin { function addModuleEntryGraph (moduleId, relation) { if (typeof moduleId !== 'number') return - if (!moduleEntryGraphMap.has(moduleId)) moduleEntryGraphMap.set(moduleId, { target: !!(relation && relation.target), children: new Set(), parents: new Set() }) + if (!moduleEntryGraphMap.has(moduleId)) moduleEntryGraphMap.set(moduleId, { + target: !!(relation && relation.target), + children: new Set(), + parents: new Set() + }) const value = moduleEntryGraphMap.get(moduleId) if (Array.isArray(relation.children)) { @@ -369,6 +373,7 @@ class SizeReportPlugin { } } } + divideEquallySize(sharedModulesGroupsSet, fillInfo.size) divideEquallySize(customGroupSharedModulesGroupsSet, fillInfo.size) } @@ -490,7 +495,8 @@ class SizeReportPlugin { totalSize: 0, staticSize: 0, chunkSize: 0, - copySize: 0 + copySize: 0, + webpackTemplateSize: 0 } function fillPackagesSizeInfo (packageName, size) { @@ -588,7 +594,6 @@ class SizeReportPlugin { packageName, size, modules: [] - // webpackTemplateSize: 0 } assetsSizeInfo.assets.push(chunkAssetInfo) fillPackagesSizeInfo(packageName, size) @@ -626,8 +631,7 @@ class SizeReportPlugin { chunkAssetInfo.modules.push(moduleData) size -= moduleSize } - - // chunkAssetInfo.webpackTemplateSize = size + sizeSummary.webpackTemplateSize += size // filter sourcemap } else if (!/\.m?js\.map$/i.test(name)) { // static copy assets such as project.config.json @@ -765,7 +769,7 @@ class SizeReportPlugin { assetsSizeInfo.assets.forEach((asset) => { if (asset.modules) sortAndFormat(asset.modules) }) - 'totalSize|staticSize|chunkSize|copySize'.split('|').forEach((key) => { + 'totalSize|staticSize|chunkSize|copySize|webpackTemplateSize'.split('|').forEach((key) => { sizeSummary[key] = formatSize(sizeSummary[key]) }) From 79de133522ebf77e2cfdf015686e4782192d9448 Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Wed, 20 Sep 2023 16:05:43 +0800 Subject: [PATCH 58/59] fix lint --- packages/size-report/src/SizeReportPlugin.js | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/size-report/src/SizeReportPlugin.js b/packages/size-report/src/SizeReportPlugin.js index 4bb7ab735e..31477aec9b 100644 --- a/packages/size-report/src/SizeReportPlugin.js +++ b/packages/size-report/src/SizeReportPlugin.js @@ -132,11 +132,13 @@ class SizeReportPlugin { function addModuleEntryGraph (moduleId, relation) { if (typeof moduleId !== 'number') return - if (!moduleEntryGraphMap.has(moduleId)) moduleEntryGraphMap.set(moduleId, { - target: !!(relation && relation.target), - children: new Set(), - parents: new Set() - }) + if (!moduleEntryGraphMap.has(moduleId)) { + moduleEntryGraphMap.set(moduleId, { + target: !!(relation && relation.target), + children: new Set(), + parents: new Set() + }) + } const value = moduleEntryGraphMap.get(moduleId) if (Array.isArray(relation.children)) { From 27b660de5151a816d59f6da078d4cceafcafe4c3 Mon Sep 17 00:00:00 2001 From: chuan Date: Mon, 25 Sep 2023 18:40:41 +0800 Subject: [PATCH 59/59] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81PropType?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/core/@types/index.d.ts | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/packages/core/@types/index.d.ts b/packages/core/@types/index.d.ts index b21e2d3a9f..f688652d79 100644 --- a/packages/core/@types/index.d.ts +++ b/packages/core/@types/index.d.ts @@ -31,18 +31,22 @@ type ArrayType = T extends Array ? R : never; // Mpx types type Data = object | (() => object) -type PropType = StringConstructor | NumberConstructor | BooleanConstructor | ObjectConstructor | ArrayConstructor | null +type PropConstructor = { + new (...args: any[]): T & {}; +} | { + (): T; +} -interface PropOpt { - type: PropType - optionalTypes?: Array - value?: any +export type PropType = PropConstructor - observer? (value: any, old: any, changedPath: string): void +type FullPropType = { + type: PropType; + value?: T; + optionalTypes?: PropType[]; } interface Properties { - [key: string]: WechatMiniprogram.Component.AllProperty + [key: string]: WechatMiniprogram.Component.AllProperty | PropType | FullPropType } interface Methods { @@ -78,8 +82,12 @@ type PropValueType = Def extends { } ? T : Def extends (...args: any[]) => infer T - ? T - : any; + ? T + : Def extends FullPropType + ? T + : Def extends PropType + ? T + : any; type GetPropsType = { readonly [K in keyof T]: PropValueType