Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

开启optimizeSize时压缩组件名称和路径 #1517

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions packages/core/src/core/transferOptions.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import { warn, findItem } from '@mpxjs/utils'

export default function transferOptions (options, type, needConvert = true) {
let currentInject
if (global.currentInject && global.currentInject.moduleId === global.currentModuleId) {
currentInject = global.currentInject
// currentModuleId -> _mid
// currentInject -> _cj
if (global._cj && global._cj.moduleId === global._mid) {
currentInject = global._cj
}
// 文件编译路径
options.mpxFileResource = global.currentResource
Expand All @@ -28,7 +30,8 @@ export default function transferOptions (options, type, needConvert = true) {
options.mixins.push(currentInject.pageEvents)
}
// 转换mode
options.mpxConvertMode = options.mpxConvertMode || getConvertMode(global.currentSrcMode)
// currentSrcMode -> _sm
options.mpxConvertMode = options.mpxConvertMode || getConvertMode(global._sm)
const rawOptions = mergeOptions(options, type, needConvert)

if (currentInject && currentInject.propKeys) {
Expand Down
5 changes: 3 additions & 2 deletions packages/core/src/platform/createApp.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,15 +82,16 @@ export default function createApp (option, config = {}) {

if (__mpx_mode__ === 'web') {
global.__mpxOptionsMap = global.__mpxOptionsMap || {}
global.__mpxOptionsMap[global.currentModuleId] = defaultOptions
// currentModuleId -> _mid
global.__mpxOptionsMap[global._mid] = defaultOptions
global.getApp = function () {
if (!isBrowser) {
console.error('[Mpx runtime error]: Dangerous API! global.getApp method is running in non browser environments')
}
return appData
}
} else {
const ctor = config.customCtor || global.currentCtor || App
const ctor = config.customCtor || global._ctor || App
ctor(defaultOptions)
}
}
16 changes: 10 additions & 6 deletions packages/core/src/platform/patch/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,16 @@ export default function createFactory (type) {
options.__pageCtor__ = true
}
} else {
if (global.currentCtor) {
ctor = global.currentCtor
if (global.currentCtorType === 'page') {
// currentCtor -> _ctor
if (global._ctor) {
ctor = global._ctor
// currentCtorType -> _ctorT
if (global._ctorT === 'page') {
options.__pageCtor__ = true
}
if (global.currentResourceType && global.currentResourceType !== type) {
error(`The ${global.currentResourceType} [${global.currentResource}] is not supported to be created by ${type} constructor.`)
// currentResourceType -> _crt
if (global._crt && global._crt !== type) {
error(`The ${global._crt} [${global.currentResource}] is not supported to be created by ${type} constructor.`)
}
} else {
if (type === 'page') {
Expand Down Expand Up @@ -59,7 +62,8 @@ export default function createFactory (type) {
const defaultOptions = getDefaultOptions(type, { rawOptions, currentInject })
if (__mpx_mode__ === 'web') {
global.__mpxOptionsMap = global.__mpxOptionsMap || {}
global.__mpxOptionsMap[global.currentModuleId] = defaultOptions
// currentModuleId -> _mid
global.__mpxOptionsMap[global._mid] = defaultOptions
} else if (ctor) {
return ctor(defaultOptions)
}
Expand Down
16 changes: 11 additions & 5 deletions packages/webpack-plugin/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,9 @@ const stringifyLoadersAndResource = require('./utils/stringify-loaders-resource'
const emitFile = require('./utils/emit-file')
const { MPX_PROCESSED_FLAG, MPX_DISABLE_EXTRACTOR_CACHE } = require('./utils/const')
const isEmptyObject = require('./utils/is-empty-object')
const { generateVariableNameBySource, isProductionLikeMode } = require('./utils/optimize-compress')
require('./utils/check-core-version-match')

const isProductionLikeMode = options => {
return options.mode === 'production' || !options.mode
}

const isStaticModule = module => {
if (!module.resource) return false
const { queryObj } = parseRequest(module.resource)
Expand Down Expand Up @@ -670,6 +667,7 @@ class MpxWebpackPlugin {
},
asyncSubpackageRules: this.options.asyncSubpackageRules,
optimizeRenderRules: this.options.optimizeRenderRules,
optimizeSize: this.options.optimizeSize,
pathHash: (resourcePath) => {
if (this.options.pathHashMode === 'relative' && this.options.projectRoot) {
return hash(path.relative(this.options.projectRoot, resourcePath))
Expand Down Expand Up @@ -701,7 +699,15 @@ class MpxWebpackPlugin {
const customOutputPath = this.options.customOutputPath
if (conflictPath) return conflictPath.replace(/(\.[^\\/]+)?$/, match => hash + match)
if (typeof customOutputPath === 'function') return customOutputPath(type, name, hash, ext).replace(/^\//, '')
if (type === 'component' || type === 'page') return path.join(type + 's', name + hash, 'index' + ext)
if (type === 'component') {
if (this.options.optimizeSize && isProductionLikeMode(compiler.options)) {
const pathHash = generateVariableNameBySource(resourcePath, 'componentPath')
return path.join('c', pathHash, 'i' + ext)
} else {
return path.join('c', name + hash, 'i' + ext)
}
}
if (type === 'page') return path.join(type + 's', name + hash, 'index' + ext)
return path.join(type, name + hash + ext)
},
extractedFilesCache: new Map(),
Expand Down
36 changes: 36 additions & 0 deletions packages/webpack-plugin/lib/json-compiler/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const resolveTabBarPath = require('../utils/resolve-tab-bar-path')
const normalize = require('../utils/normalize')
const mpxViewPath = normalize.lib('runtime/components/ali/mpx-view.mpx')
const mpxTextPath = normalize.lib('runtime/components/ali/mpx-text.mpx')
const { generateVariableNameBySource, isProductionLikeMode } = require('../utils/optimize-compress')

module.exports = function (content) {
const nativeCallback = this.async()
Expand Down Expand Up @@ -256,6 +257,35 @@ module.exports = function (content) {
}
}

const processOptimizeSize = (json, callback) => {
if (mpx.optimizeSize && isProductionLikeMode(this)) {
// placeholder 替换
if (json.componentPlaceholder) {
const newComponentPlaceholder = {}
for (const [name, value] of Object.entries(json.componentPlaceholder)) {
const newName = generateVariableNameBySource(name, this.resourcePath + 'componentName')
newComponentPlaceholder[newName] = json.componentPlaceholder[name]
delete json.componentPlaceholder[name]
if (value in json.usingComponents) {
newComponentPlaceholder[newName] = generateVariableNameBySource(value, this.resourcePath + 'componentName')
}
}
Object.assign(json.componentPlaceholder, newComponentPlaceholder)
}
// usingComponents 替换
if (json.usingComponents) {
const newUsingComponents = {}
for (const name of Object.keys(json.usingComponents)) {
const newName = generateVariableNameBySource(name, this.resourcePath + 'componentName')
newUsingComponents[newName] = json.usingComponents[name]
delete json.usingComponents[name]
}
Object.assign(json.usingComponents, newUsingComponents)
}
}
callback()
}

if (isApp) {
// app.json
const localPages = []
Expand Down Expand Up @@ -605,6 +635,9 @@ module.exports = function (content) {
}

async.parallel([
(callback) => {
processOptimizeSize(json, callback)
},
(callback) => {
// 添加首页标识
if (json.pages && json.pages[0]) {
Expand Down Expand Up @@ -683,6 +716,9 @@ module.exports = function (content) {
}
}
async.parallel([
(callback) => {
processOptimizeSize(json, callback)
},
(callback) => {
processComponents(json.usingComponents, this.context, callback)
},
Expand Down
16 changes: 10 additions & 6 deletions packages/webpack-plugin/lib/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,8 @@ module.exports = function (content) {
}

// 注入模块id及资源路径
output += `global.currentModuleId = ${JSON.stringify(moduleId)}\n`
// currentModuleId -> _mid
output += `global._mid = ${JSON.stringify(moduleId)}\n`
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

都简化了就简化彻底一点吧,比如global._id, global._i, global._i.r

if (!isProduction) {
output += `global.currentResource = ${JSON.stringify(filePath)}\n`
}
Expand Down Expand Up @@ -279,12 +280,14 @@ module.exports = function (content) {
: ctorType === 'component'
? 'Component'
: 'App'

output += `global.currentCtor = ${ctor}\n`
output += `global.currentCtorType = ${JSON.stringify(ctor.replace(/^./, (match) => {
// currentCtor -> _ctor
output += `global._ctor = ${ctor}\n`
// currentCtorType -> _ctorT
output += `global._ctorT = ${JSON.stringify(ctor.replace(/^./, (match) => {
return match.toLowerCase()
}))}\n`
output += `global.currentResourceType = ${JSON.stringify(ctorType)}\n`
// currentResourceType -> _crt
output += `global._crt = ${JSON.stringify(ctorType)}\n`

// template
output += '/* template */\n'
Expand Down Expand Up @@ -345,7 +348,8 @@ module.exports = function (content) {
const script = parts.script || {}
if (script) {
scriptSrcMode = script.mode || scriptSrcMode
if (scriptSrcMode) output += `global.currentSrcMode = ${JSON.stringify(scriptSrcMode)}\n`
// currentSrcMode -> _sm
if (scriptSrcMode) output += `global._sm = ${JSON.stringify(scriptSrcMode)}\n`
// 传递ctorType以补全js内容
const extraOptions = {
...script.src
Expand Down
16 changes: 10 additions & 6 deletions packages/webpack-plugin/lib/native-loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -241,19 +241,23 @@ module.exports = function (content) {
}

// 注入模块id及资源路径
let output = `global.currentModuleId = ${JSON.stringify(moduleId)}\n`
// currentModuleId -> _mid
let output = `global._mid = ${JSON.stringify(moduleId)}\n`
if (!isProduction) {
output += `global.currentResource = ${JSON.stringify(filePath)}\n`
}

output += `global.currentCtor = ${ctor}\n`
output += `global.currentCtorType = ${JSON.stringify(ctor.replace(/^./, (match) => {
// currentCtor -> _ctor
output += `global._ctor = ${ctor}\n`
// currentCtorType -> _ctorT
output += `global._ctorT = ${JSON.stringify(ctor.replace(/^./, (match) => {
return match.toLowerCase()
}))}\n`
output += `global.currentResourceType = ${JSON.stringify(ctorType)}\n`
// currentResourceType -> _crt
output += `global._crt = ${JSON.stringify(ctorType)}\n`

if (srcMode) {
output += `global.currentSrcMode = ${JSON.stringify(srcMode)}\n`
// currentSrcMode -> _sm
output += `global._sm = ${JSON.stringify(srcMode)}\n`
}

for (const type in typeResourceMap) {
Expand Down
32 changes: 32 additions & 0 deletions packages/webpack-plugin/lib/template-compiler/compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const transDynamicClassExpr = require('./trans-dynamic-class-expr')
const dash2hump = require('../utils/hump-dash').dash2hump
const makeMap = require('../utils/make-map')
const { isNonPhrasingTag } = require('../utils/dom-tag-config')
const { isProductionLikeMode, generateVariableNameBySource } = require('../utils/optimize-compress')

const no = function () {
return false
Expand Down Expand Up @@ -788,6 +789,10 @@ function parse (template, options) {
arr.length && warn$1(`\n ${options.filePath} \n 组件 ${arr.join(' | ')} 注册了,但是未被对应的模板引用,建议删除!`)
}

if (options.optimizeSize && isProductionLikeMode(this)) {
processOptimizeSize(root, options)
}

return {
root,
meta
Expand Down Expand Up @@ -2213,6 +2218,33 @@ function postProcessComponentIs (el) {
return el
}

function processOptimizeSize (root, options) {
const { usingComponents, filePath } = options
function walkNode (root, callback) {
if (!root) return
callback(root)
if (Array.isArray(root.children) && root.children.length) {
for (const node of root.children) {
if (!node) continue
walkNode(node, callback)
}
}
}
// 记录所有原生组件(判断条件:usingComponents中不存在的组件)
const nativeTags = new Set()
walkNode(root, (node) => {
if (node.tag && usingComponents.indexOf(node.tag) === -1) {
nativeTags.add(node.tag)
}
})
walkNode(root, (node) => {
// 只有自定义组件才替换(判断条件:在usingComponents中的组件),并且新组件名不允许出现原生组件名
if (node.tag && usingComponents.indexOf(node.tag) !== -1) {
node.tag = generateVariableNameBySource(node.tag, filePath + 'componentName', [...nativeTags])
}
})
}

function stringifyAttr (val) {
if (typeof val === 'string') {
const hasSingle = val.indexOf('\'') > -1
Expand Down
14 changes: 8 additions & 6 deletions packages/webpack-plugin/lib/template-compiler/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ module.exports = function (raw) {
const env = mpx.env
const defs = mpx.defs
const i18n = mpx.i18n
const optimizeSize = mpx.optimizeSize
const externalClasses = mpx.externalClasses
const decodeHTMLText = mpx.decodeHTMLText
const globalSrcMode = mpx.srcMode
Expand Down Expand Up @@ -68,6 +69,7 @@ module.exports = function (raw) {
// 这里需传递resourcePath和wxsContentMap保持一致
filePath: resourcePath,
i18n,
optimizeSize,
checkUsingComponents: matchCondition(resourcePath, mpx.checkUsingComponentsRules),
globalComponents: Object.keys(mpx.usingComponents),
forceProxyEvent: matchCondition(resourcePath, mpx.forceProxyEventRules),
Expand All @@ -92,9 +94,9 @@ module.exports = function (raw) {
const src = loaderUtils.urlToRequest(meta.wxsModuleMap[module], root)
resultSource += `var ${module} = require(${loaderUtils.stringifyRequest(this, src)});\n`
}

// currentInject -> _cj
resultSource += `
global.currentInject = {
global._cj = {
moduleId: ${JSON.stringify(moduleId)}
};\n`

Expand All @@ -117,7 +119,7 @@ global.currentInject = {
ignoreMap
})
resultSource += `
global.currentInject.render = function (_i, _c, _r, _sc) {
global._cj.render = function (_i, _c, _r, _sc) {
${bindResult.code}
_r(${optimizeRenderLevel === 2 ? 'true' : ''});
};\n`
Expand All @@ -139,20 +141,20 @@ ${e.stack}`)

if (meta.computed) {
resultSource += bindThis.transform(`
global.currentInject.injectComputed = {
global._cj.injectComputed = {
${meta.computed.join(',')}
};`).code + '\n'
}

if (meta.refs) {
resultSource += `
global.currentInject.getRefsData = function () {
global._cj.getRefsData = function () {
return ${JSON.stringify(meta.refs)};
};\n`
}

if (meta.options) {
resultSource += `global.currentInject.injectOptions = ${JSON.stringify(meta.options)};` + '\n'
resultSource += `global._cj.injectOptions = ${JSON.stringify(meta.options)};` + '\n'
}

this.emitFile(resourcePath, '', undefined, {
Expand Down
Loading
Loading