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 all 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 -> _id
// currentInject -> _j
if (global._j && global._j.moduleId === global._id) {
currentInject = global._j
}
// 文件编译路径
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 -> _id
global.__mpxOptionsMap[global._id] = defaultOptions
global.getApp = function () {
if (!isBrowser) {
console.error('[Mpx runtime error]: Dangerous API! global.getApp method is running in non browser environments')
}
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 -> _id
global.__mpxOptionsMap[global._id] = defaultOptions
} else if (ctor) {
return ctor(defaultOptions)
}
Expand Down
22 changes: 17 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 @@ -174,6 +171,11 @@ class MpxWebpackPlugin {
options.optimizeRenderRules = options.optimizeRenderRules ? (Array.isArray(options.optimizeRenderRules) ? options.optimizeRenderRules : [options.optimizeRenderRules]) : []
options.retryRequireAsync = options.retryRequireAsync || false
options.optimizeSize = options.optimizeSize || false
// 保留组件名(压缩后组件名不允许出现)
if (typeof options.reservedComponentName === 'object') {
options.reservedComponentName = options.reservedComponentName[options.mode]
}
options.reservedComponentName = options.reservedComponentName || []
this.options = options
// Hack for buildDependencies
const rawResolveBuildDependencies = FileSystemInfo.prototype.resolveBuildDependencies
Expand Down Expand Up @@ -670,6 +672,8 @@ class MpxWebpackPlugin {
},
asyncSubpackageRules: this.options.asyncSubpackageRules,
optimizeRenderRules: this.options.optimizeRenderRules,
optimizeSize: this.options.optimizeSize,
reservedComponentName: this.options.reservedComponentName,
pathHash: (resourcePath) => {
if (this.options.pathHashMode === 'relative' && this.options.projectRoot) {
return hash(path.relative(this.options.projectRoot, resourcePath))
Expand Down Expand Up @@ -701,7 +705,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
37 changes: 37 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 { isProductionLikeMode } = require('../utils/optimize-compress')

module.exports = function (content) {
const nativeCallback = this.async()
Expand All @@ -43,6 +44,7 @@ module.exports = function (content) {
const localSrcMode = queryObj.mode
const srcMode = localSrcMode || globalSrcMode
const projectRoot = mpx.projectRoot
const usingComponentsNameMap = JSON.parse(queryObj.usingComponentsNameMap)

const isApp = !(pagesMap[resourcePath] || componentsMap[resourcePath])
const publicPath = this._compilation.outputOptions.publicPath || ''
Expand Down Expand Up @@ -256,6 +258,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 = usingComponentsNameMap[name]
newComponentPlaceholder[newName] = json.componentPlaceholder[name]
delete json.componentPlaceholder[name]
if (value in json.usingComponents) {
newComponentPlaceholder[newName] = usingComponentsNameMap[value]
}
}
Object.assign(json.componentPlaceholder, newComponentPlaceholder)
}
// usingComponents 替换
if (json.usingComponents) {
const newUsingComponents = {}
for (const name of Object.keys(json.usingComponents)) {
const newName = usingComponentsNameMap[name]
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 +636,9 @@ module.exports = function (content) {
}

async.parallel([
(callback) => {
processOptimizeSize(json, callback)
},
(callback) => {
// 添加首页标识
if (json.pages && json.pages[0]) {
Expand Down Expand Up @@ -683,6 +717,9 @@ module.exports = function (content) {
}
}
async.parallel([
(callback) => {
processOptimizeSize(json, callback)
},
(callback) => {
processComponents(json.usingComponents, this.context, callback)
},
Expand Down
40 changes: 29 additions & 11 deletions packages/webpack-plugin/lib/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const { MPX_APP_MODULE_ID } = require('./utils/const')
const path = require('path')
const processMainScript = require('./web/processMainScript')
const getRulesRunner = require('./platform')
const { CompressName } = require('./utils/optimize-compress.js')

module.exports = function (content) {
this.cacheable()
Expand Down Expand Up @@ -50,6 +51,7 @@ module.exports = function (content) {
const localSrcMode = queryObj.mode
const srcMode = localSrcMode || globalSrcMode
const autoScope = matchCondition(resourcePath, mpx.autoScopeRules)
const compressName = new CompressName()

const emitWarning = (msg) => {
this.emitWarning(
Expand Down Expand Up @@ -113,7 +115,10 @@ module.exports = function (content) {
const hasComment = templateAttrs && templateAttrs.comments
const isNative = false

let usingComponents = [].concat(Object.keys(mpx.usingComponents))
const usingComponentsNameMap = {}
for (const name in mpx.usingComponents) {
usingComponentsNameMap[name] = name // compressName._generateName()
}
let componentPlaceholder = []
let componentGenerics = {}

Expand All @@ -134,7 +139,11 @@ module.exports = function (content) {
const ret = JSON5.parse(parts.json.content)
if (rulesRunner) rulesRunner(ret)
if (ret.usingComponents) {
usingComponents = usingComponents.concat(Object.keys(ret.usingComponents))
for (const name in ret.usingComponents) {
// Object.keys(mpx.usingComponents): 压缩组件名,禁止与全局组件同名
// mpx.reservedComponentName 禁止与保留组件名重复(如 text/view/ad 等)
usingComponentsNameMap[name] = ctorType === 'app' ? name : compressName._occupiedGenerateName([...Object.keys(mpx.usingComponents), ...mpx.reservedComponentName])
}
}
if (ret.componentPlaceholder) {
componentPlaceholder = componentPlaceholder.concat(Object.values(ret.componentPlaceholder))
Expand Down Expand Up @@ -192,7 +201,7 @@ module.exports = function (content) {
srcMode,
moduleId,
ctorType,
usingComponents,
usingComponentsNameMap,
componentGenerics
}, callback)
},
Expand Down Expand Up @@ -249,7 +258,8 @@ module.exports = function (content) {
}

// 注入模块id及资源路径
output += `global.currentModuleId = ${JSON.stringify(moduleId)}\n`
// currentModuleId -> _id
output += `global._id = ${JSON.stringify(moduleId)}\n`
if (!isProduction) {
output += `global.currentResource = ${JSON.stringify(filePath)}\n`
}
Expand Down Expand Up @@ -279,12 +289,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 All @@ -299,7 +311,7 @@ module.exports = function (content) {
hasComment,
isNative,
moduleId,
usingComponents,
usingComponentsNameMap: JSON.stringify(usingComponentsNameMap),
componentPlaceholder
// 添加babel处理渲染函数中可能包含的...展开运算符
// 由于...运算符应用范围极小以及babel成本极高,先关闭此特性后续看情况打开
Expand Down Expand Up @@ -336,7 +348,12 @@ module.exports = function (content) {
output += '/* json */\n'
// 给予json默认值, 确保生成json request以自动补全json
const json = parts.json || {}
output += getRequire('json', json, json.src && { ...queryObj, resourcePath }) + '\n'
output += getRequire('json', json, {
...(json.src
? { ...queryObj, resourcePath }
: null),
usingComponentsNameMap: JSON.stringify(usingComponentsNameMap)
}) + '\n'

// script
output += '/* script */\n'
Expand All @@ -345,7 +362,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 -> _id
let output = `global._id = ${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
Loading
Loading