提交 24c04594 编写于 作者: fxy060608's avatar fxy060608

init cli

上级 bebdee4a
src/core/helpers/html-parser.js
src/platforms/app-plus-nvue/runtime
build/rollup-plugin-require-context
packages/*/packages
{
"npmClient": "yarn",
"useWorkspaces": false,
"packages": [
"packages/*"
],
"version": "0.9.50"
}
......@@ -3,6 +3,7 @@
"version": "0.0.1",
"scripts": {
"lint": "eslint --fix --config package.json --ext .js --ext .vue --ignore-path .eslintignore build src",
"lint:cli": "eslint --fix --config package.json --ignore-path .eslintignore packages/uni-cli-shared packages/uni-template-compiler \"packages/vue-cli-*/**/*.js\" \"packages/webpack-uni-*/**/*.js\"",
"dev:h5": "npm run lint && cross-env NODE_ENV=production UNI_WATCH=true UNI_PLATFORM=h5 node build/build.js",
"build:h5": "npm run lint && cross-env NODE_ENV=production UNI_WATCH=false UNI_PLATFORM=h5 node build/build.js",
"build:app-plus": "cross-env UNI_PLATFORM=app-plus rollup -c build/rollup.config.mp.js",
......@@ -81,8 +82,8 @@
"Vue": true,
"wx": true,
"my": true,
"swan": true,
"weex": true,
"swan": true,
"weex": true,
"__id__": true,
"__uniConfig": true,
"__uniRoutes": true,
......@@ -93,7 +94,10 @@
"__VERSION__": true,
"__GLOBAL__": true,
"__PLATFORM_TITLE__": true,
"__PLATFORM_PREFIX__": true
"__PLATFORM_PREFIX__": true,
"it": true,
"describe": true,
"expect": true
},
"rules": {
"no-tabs": 0,
......
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
\ No newline at end of file
const {
updateAppJson,
updatePageJson,
updateUsingComponents,
getChangedJsonFileMap
} = require('../lib/cache')
describe('shared:cache', () => {
it('generate app.json', () => {
const name = 'app'
const appJson = {
debug: true
}
updateAppJson(name, appJson)
let appJsonStr = getChangedJsonFileMap().get(name + '.json')
expect(appJsonStr).toBe(JSON.stringify(appJson, null, 2))
expect(0).toBe(getChangedJsonFileMap().size)
appJson.resizable = true
updateAppJson(name, appJson)
appJsonStr = getChangedJsonFileMap().get(name + '.json')
expect(appJsonStr).toBe(JSON.stringify(appJson, null, 2))
expect(0).toBe(getChangedJsonFileMap().size)
const usingComponents = {
'my-component': '/components/component-tag-name'
}
updateUsingComponents('app', usingComponents)
appJsonStr = getChangedJsonFileMap().get(name + '.json')
appJson.usingComponents = usingComponents
expect(appJsonStr).toBe(JSON.stringify(appJson, null, 2))
})
it('generate page.json', () => {
const name = 'page/index/index'
const pageJson = {
navigationBarBackgroundColor: '#ffffff'
}
updatePageJson(name, pageJson)
let pageJsonStr = getChangedJsonFileMap().get(name + '.json')
expect(pageJsonStr).toBe(JSON.stringify(pageJson, null, 2))
expect(0).toBe(getChangedJsonFileMap().size)
pageJson.navigationBarTextStyle = 'black'
updatePageJson(name, pageJson)
pageJsonStr = getChangedJsonFileMap().get(name + '.json')
expect(pageJsonStr).toBe(JSON.stringify(pageJson, null, 2))
expect(0).toBe(getChangedJsonFileMap().size)
const usingComponents = {
'my-component1': '/components/component-tag-name1'
}
updateUsingComponents(name, usingComponents)
pageJsonStr = getChangedJsonFileMap().get(name + '.json')
pageJson.usingComponents = usingComponents
expect(pageJsonStr).toBe(JSON.stringify(pageJson, null, 2))
})
it('generate component.json', () => {
const name = 'components/component-tag-name'
let usingComponents = {
'my-component': '/components/component-tag-name'
}
updateUsingComponents(name, usingComponents, 'Component')
let componentJsonStr = getChangedJsonFileMap().get(name + '.json')
expect(componentJsonStr).toBe(JSON.stringify({
usingComponents,
component: true
}, null, 2))
expect(0).toBe(getChangedJsonFileMap().size)
usingComponents = {}
updateUsingComponents(name, usingComponents, 'Component')
componentJsonStr = getChangedJsonFileMap().get(name + '.json')
expect(componentJsonStr).toBe(JSON.stringify({
usingComponents,
component: true
}, null, 2))
expect(0).toBe(getChangedJsonFileMap().size)
})
})
function parseApis (modules, test) {
return modules.reduce(function (apis, module) {
const apiList = module.apiList
apiList && Object.keys(apiList).forEach(name => {
if (test(name, apiList[name])) {
apis.add(name.replace('uni.', ''))
}
})
return apis
}, new Set())
}
module.exports = {
parseUserApis (configModules = [], allModules = []) {
const blackboxApis = parseApis(configModules, function (name, value) {
return value === false
})
const allApis = parseApis(allModules, function () {
return true
})
return [...allApis].filter(name => !blackboxApis.has(name))
}
}
/**
* 1.page-loader 缓存基础的 app.json page.json project.config.json
* 2.main-loader 缓存 app.json 中的 usingComponents 节点
* 3.script-loader 修改缓存 usingComponents 节点
* 5.webpack plugin 中获取被修改的 page.json,component.json 并 emitFile
*/
const jsonFileMap = new Map()
const changedJsonFileSet = new Set()
const componentSet = new Set()
const pageSet = new Set()
let globalUsingComponents = Object.create(null)
let appJsonUsingComponents = Object.create(null)
let componentSpecialMethods = Object.create(null)
function getPagesJson () {
if (process.env.UNI_PLATFORM === 'h5') {
return process.UNI_H5_PAGES_JSON
}
const pagesJson = {
pages: {}
}
for (let name of pageSet.values()) {
const style = JSON.parse(getJsonFile(name) || '{}')
delete style.customUsingComponents
pagesJson.pages[name] = style
}
const appJson = JSON.parse(getJsonFile('app') || '{}')
pagesJson.globalStyle = appJson['window'] || {}
return pagesJson
}
function updateJsonFile (name, jsonStr) {
changedJsonFileSet.add(name)
if (typeof jsonStr !== 'string') {
jsonStr = JSON.stringify(jsonStr, null, 2)
}
jsonFileMap.set(name, jsonStr)
}
function getJsonFile (name) {
return jsonFileMap.get(name)
}
function getChangedJsonFileMap (clear = true) {
const changedJsonFileMap = new Map()
for (let name of changedJsonFileSet.values()) {
changedJsonFileMap.set(name + '.json', jsonFileMap.get(name))
}
clear && changedJsonFileSet.clear()
return changedJsonFileMap
}
function updateAppJson (name, jsonObj) {
updateComponentJson(name, jsonObj)
}
function updatePageJson (name, jsonObj) {
pageSet.add(name)
updateComponentJson(name, jsonObj)
}
function updateProjectJson (name, jsonObj) {
updateComponentJson(name, jsonObj, false)
}
const supportGlobalUsingComponents = process.env.UNI_PLATFORM === 'mp-weixin' || process.env.UNI_PLATFORM === 'mp-qq'
function updateComponentJson (name, jsonObj, usingComponents = true) {
const oldJsonStr = getJsonFile(name)
if (oldJsonStr) { // update
if (usingComponents) { // merge usingComponents
jsonObj.usingComponents = JSON.parse(oldJsonStr).usingComponents || {}
}
const newJsonStr = JSON.stringify(jsonObj, null, 2)
if (newJsonStr !== oldJsonStr) {
updateJsonFile(name, newJsonStr)
}
} else { // add
updateJsonFile(name, jsonObj)
}
}
function updateUsingGlobalComponents (name, usingGlobalComponents) {
if (supportGlobalUsingComponents) {
return
}
const oldJsonStr = getJsonFile(name)
if (oldJsonStr) { // update
const jsonObj = JSON.parse(oldJsonStr)
jsonObj.usingGlobalComponents = usingGlobalComponents
const newJsonStr = JSON.stringify(jsonObj, null, 2)
if (newJsonStr !== oldJsonStr) {
updateJsonFile(name, newJsonStr)
}
} else { // add
const jsonObj = {
usingGlobalComponents
}
updateJsonFile(name, jsonObj)
}
}
function updateUsingComponents (name, usingComponents, type) {
if (type === 'Component') {
componentSet.add(name)
}
if (type === 'App') { // 记录全局组件
globalUsingComponents = usingComponents
}
const oldJsonStr = getJsonFile(name)
if (oldJsonStr) { // update
const jsonObj = JSON.parse(oldJsonStr)
if (type === 'Component') {
jsonObj.component = true
} else if (type === 'Page') {
if (process.env.UNI_PLATFORM === 'mp-baidu') {
jsonObj.component = true
}
}
jsonObj.usingComponents = usingComponents
const newJsonStr = JSON.stringify(jsonObj, null, 2)
if (newJsonStr !== oldJsonStr) {
updateJsonFile(name, newJsonStr)
}
} else { // add
const jsonObj = {
usingComponents
}
if (type === 'Component') {
jsonObj.component = true
} else if (type === 'Page') {
if (process.env.UNI_PLATFORM === 'mp-baidu') {
jsonObj.component = true
}
}
updateJsonFile(name, jsonObj)
}
}
function updateComponentGenerics (name, componentGenerics) {
const oldJsonStr = getJsonFile(name)
if (oldJsonStr) { // update
const jsonObj = JSON.parse(oldJsonStr)
jsonObj.componentGenerics = componentGenerics
const newJsonStr = JSON.stringify(jsonObj, null, 2)
if (newJsonStr !== oldJsonStr) {
updateJsonFile(name, newJsonStr)
}
} else { // add
const jsonObj = {
componentGenerics
}
updateJsonFile(name, jsonObj)
}
}
function updateGenericComponents (name, genericComponents) {
const oldJsonStr = getJsonFile(name)
if (oldJsonStr) { // update
const jsonObj = JSON.parse(oldJsonStr)
jsonObj.genericComponents = genericComponents
const newJsonStr = JSON.stringify(jsonObj, null, 2)
if (newJsonStr !== oldJsonStr) {
updateJsonFile(name, newJsonStr)
}
} else { // add
const jsonObj = {
genericComponents
}
updateJsonFile(name, jsonObj)
}
}
function updateAppJsonUsingComponents (usingComponents) {
appJsonUsingComponents = usingComponents
}
function getComponentSet () {
return componentSet
}
function getGlobalUsingComponents () {
// 合并 app.json ,main.js 全局组件
return Object.assign({}, appJsonUsingComponents, globalUsingComponents)
}
function getWXComponents (name) {
const oldJsonStr = getJsonFile(name)
if (oldJsonStr) {
const jsonObj = JSON.parse(oldJsonStr)
if (jsonObj.customUsingComponents) {
return Object.assign({}, appJsonUsingComponents, jsonObj.customUsingComponents)
}
}
return Object.assign({}, appJsonUsingComponents)
}
function updateSpecialMethods (name, specialMethods) {
if (specialMethods.length) {
componentSpecialMethods[name] = specialMethods
} else {
delete componentSpecialMethods[name]
}
}
function getSpecialMethods (name) {
if (!name) {
return componentSpecialMethods
}
return componentSpecialMethods[name] || []
}
module.exports = {
getPageSet () {
return pageSet
},
getJsonFileMap () {
return jsonFileMap
},
getJsonFile,
getPagesJson,
getComponentSet,
getWXComponents,
getGlobalUsingComponents,
updateAppJson,
updatePageJson,
updateProjectJson,
updateComponentJson,
updateSpecialMethods,
updateUsingComponents,
updateUsingGlobalComponents,
updateAppJsonUsingComponents,
updateComponentGenerics,
updateGenericComponents,
getChangedJsonFileMap,
getSpecialMethods
}
const tags = require('./tags')
const {
getJson,
parseJson
} = require('./json')
const {
getH5Options,
getManifestJson,
getNetworkTimeout,
parseManifestJson
} = require('./manifest.js')
const {
getMainEntry,
getNVueMainEntry,
parseEntry,
parsePages,
getPagesJson,
parsePagesJson
} = require('./pages')
const {
md5,
hasModule,
hashify,
camelize,
hyphenate,
removeExt,
normalizePath,
getComponentName,
convertStaticStyle
} = require('./util')
const {
getFlexDirection,
getPlatformProject,
isSupportSubPackages,
getPlatforms,
getPlatformGlobal,
getPlatformScss,
getPlatformSass,
runByHBuilderX,
isInHBuilderX,
isInHBuilderXAlpha,
getPlatformExts,
getPlatformTarget,
getPlatformVue,
getPlatformCompiler,
getShadowCss,
getPlatformCssVars,
getPlatformCssnano,
getShadowTemplate,
jsPreprocessOptions,
cssPreprocessOptions,
htmlPreprocessOptions,
nvueJsPreprocessOptions,
nvueCssPreprocessOptions,
nvueHtmlPreprocessOptions,
devtoolModuleFilenameTemplate
} = require('./platform')
module.exports = {
md5,
tags,
getJson,
parseJson,
hashify,
hasModule,
camelize,
hyphenate,
removeExt,
normalizePath,
parseEntry,
parsePages,
getH5Options,
getMainEntry,
getNVueMainEntry,
getPagesJson,
getManifestJson,
getNetworkTimeout,
runByHBuilderX,
isInHBuilderX,
isInHBuilderXAlpha,
isSupportSubPackages,
getPlatforms,
getFlexDirection,
getPlatformScss,
getPlatformSass,
getPlatformExts,
getPlatformTarget,
getPlatformProject,
getPlatformVue,
getPlatformGlobal,
getShadowCss,
getPlatformCssVars,
getPlatformCssnano,
getPlatformCompiler,
getShadowTemplate,
parsePagesJson,
parseManifestJson,
getComponentName,
convertStaticStyle,
jsPreprocessOptions,
cssPreprocessOptions,
htmlPreprocessOptions,
nvueJsPreprocessOptions,
nvueCssPreprocessOptions,
nvueHtmlPreprocessOptions,
devtoolModuleFilenameTemplate
}
const fs = require('fs')
const path = require('path')
const stripJsonComments = require('strip-json-comments')
const preprocessor = require('@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader/preprocess')
const {
jsPreprocessOptions
} = require('./platform')
function parseJson (content, preprocess = false) {
if (typeof content === 'string') {
if (preprocess) {
content = preprocessor.preprocess(content, jsPreprocessOptions.context, {
type: jsPreprocessOptions.type
})
}
content = JSON.parse(stripJsonComments(content))
}
content = JSON.stringify(content)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
return JSON.parse(content)
}
function getJson (jsonFileName, preprocess = false) {
const jsonFilePath = path.resolve(process.env.UNI_INPUT_DIR, jsonFileName)
if (!fs.existsSync(jsonFilePath)) {
throw new Error(jsonFilePath + ' 不存在')
}
try {
return parseJson(fs.readFileSync(jsonFilePath, 'utf8'), preprocess)
} catch (e) {
console.error(jsonFileName + ' 解析失败')
}
}
module.exports = {
getJson,
parseJson
}
const path = require('path')
const {
getJson,
parseJson
} = require('./json')
const defaultRouter = {
mode: 'hash',
base: '/'
}
const defaultAsync = {
loading: 'AsyncLoading',
error: 'AsyncError',
delay: 200,
timeout: 3000
}
const networkTimeout = {
request: 6000,
connectSocket: 6000,
uploadFile: 6000,
downloadFile: 6000
}
function getManifestJson () {
return getJson('manifest.json')
}
function parseManifestJson (content) {
return parseJson(content)
}
function getNetworkTimeout (manifestJson) {
if (!manifestJson) {
manifestJson = getManifestJson()
}
return Object.assign({}, networkTimeout, manifestJson.networkTimeout || {})
}
function getH5Options (manifestJson) {
if (!manifestJson) {
manifestJson = getManifestJson()
}
const h5 = manifestJson.h5 || {}
h5.appid = (manifestJson.appid || '').replace('__UNI__', '')
h5.title = h5.title || manifestJson.name || ''
h5.router = Object.assign({}, defaultRouter, h5.router || {})
h5['async'] = Object.assign({}, defaultAsync, h5['async'] || {})
let base = h5.router.base
if (base.indexOf('/') !== 0) {
base = '/' + base
}
if (base.substr(-1) !== '/') {
base = base + '/'
}
h5.router.base = base
if (process.env.NODE_ENV === 'production') { // 生产模式,启用 publicPath
h5.publicPath = h5.publicPath || base
if (h5.publicPath.substr(-1) !== '/') {
h5.publicPath = h5.publicPath + '/'
}
} else { // 其他模式,启用 base
h5.publicPath = base
}
/* eslint-disable no-mixed-operators */
h5.template = h5.template && path.resolve(process.env.UNI_INPUT_DIR, h5.template) || path.resolve(__dirname,
'../../../../public/index.html')
h5.devServer = h5.devServer || {}
return h5
}
module.exports = {
getManifestJson,
parseManifestJson,
getNetworkTimeout,
getH5Options
}
const PLATFORMS = [
'h5',
'app-plus',
'mp-weixin',
'mp-qq',
'mp-baidu',
'mp-alipay',
'mp-toutiao'
]
module.exports = {
initCustomScript (name, pkgPath) {
const pkg = require(pkgPath)
const uniAppOptions = pkg['uni-app']
let scriptOptions = false
if (uniAppOptions && uniAppOptions['scripts']) {
scriptOptions = uniAppOptions['scripts'][name]
}
if (!scriptOptions) {
console.error(`package.json->uni-app->scripts->${name} 不存在`)
process.exit(0)
}
if (!scriptOptions.env || !scriptOptions.env.UNI_PLATFORM) {
console.error(`package.json->uni-app->scripts->${name}->env 不存在,必须配置 env->UNI_PLATFORM 基础平台`)
process.exit(0)
}
if (PLATFORMS.indexOf(scriptOptions.env.UNI_PLATFORM) === -1) {
console.error(`UNI_PLATFORM 支持一下平台 ${JSON.stringify(PLATFORMS)}`)
process.exit(0)
}
process.env.UNI_PLATFORM = scriptOptions.env.UNI_PLATFORM
process.UNI_SCRIPT_ENV = scriptOptions.env || {}
process.UNI_SCRIPT_DEFINE = scriptOptions.define || {}
return scriptOptions
}
}
const fs = require('fs')
const path = require('path')
const {
removeExt,
normalizePath
} = require('./util')
const {
getJson,
parseJson
} = require('./json')
let mainEntry = ''
let nvueMainEntry = ''
function getMainEntry () {
if (!mainEntry) {
mainEntry = fs.existsSync(path.resolve(process.env.UNI_INPUT_DIR, 'main.ts')) ? 'main.ts' : 'main.js'
}
return mainEntry
}
function getNVueMainEntry () {
if (!nvueMainEntry) {
nvueMainEntry = fs.existsSync(path.resolve(process.env.UNI_INPUT_DIR, 'main.js')) ? 'main.js' : '.main.js'
if (nvueMainEntry === '.main.js') {
fs.writeFileSync(path.resolve(process.env.UNI_INPUT_DIR, '.main.js'), '')
}
}
return nvueMainEntry
}
function getPagesJson () {
return processPagesJson(getJson('pages.json', true))
}
function parsePagesJson (content) {
return processPagesJson(parseJson(content, true))
}
function filterPages (pages = [], root) {
for (let i = pages.length - 1; i >= 0; i--) {
const page = pages[i]
if (!isValidPage(page, root)) {
pages.splice(i, 1)
}
}
}
function processPagesJson (pagesJson) {
let uniNVueEntryPagePath
if (pagesJson.pages && pagesJson.pages.length) { // 如果首页是 nvue
if (isNVuePage(pagesJson.pages[0])) {
uniNVueEntryPagePath = pagesJson.pages[0].path
}
}
// pages
filterPages(pagesJson.pages)
// subPackages
if (Array.isArray(pagesJson.subPackages) && pagesJson.subPackages.length) {
pagesJson.subPackages.forEach(subPackage => {
filterPages(subPackage.pages, subPackage.root)
})
}
if (Object.keys(uniNVuePages).length) { // 直接挂在 pagesJson 上
pagesJson.nvue = {
pages: uniNVuePages
}
if (uniNVueEntryPagePath) {
pagesJson.nvue.entryPagePath = uniNVueEntryPagePath
}
}
return pagesJson
}
function isNVuePage (page, root = '') {
if (process.env.UNI_PLATFORM === 'app-plus') {
const pagePath = path.join(root, page.path)
if (fs.existsSync(path.resolve(process.env.UNI_INPUT_DIR, pagePath + '.nvue'))) { // cache一下结果?如果文件被删除,cache 就会出现错误
return true
}
}
return false
}
function isValidPage (page, root = '') {
if (typeof page === 'string') { // 不合法的配置
console.warn(`${page} 配置错误, 已被忽略, 查看文档: https://uniapp.dcloud.io/collocation/pages?id=pages`)
return false
}
let pagePath = page.path
if (pagePath.indexOf('platforms') === 0) { // 平台相关
if (pagePath.indexOf('platforms/' + process.env.UNI_PLATFORM) === -1) { // 非本平台
return false
}
}
if (
process.env.UNI_PLATFORM === 'app-plus' &&
page.style
) {
const subNVues = page.style.subNVues || (page.style['app-plus'] && page.style['app-plus']['subNVues'])
if (Array.isArray(subNVues)) {
subNVues.forEach(subNVue => {
let subNVuePath = subNVue.path
if (subNVuePath) {
subNVuePath = subNVue.path.split('?')[0]
const subNVuePagePath = removeExt(path.join(root, subNVuePath))
// if (process.env.UNI_USING_NVUE_COMPILER) {
process.UNI_NVUE_ENTRY[subNVuePagePath] = getNVueMainJsPath(subNVuePagePath)
// } else {
// process.UNI_NVUE_ENTRY[subNVuePagePath] = path.resolve(process.env.UNI_INPUT_DIR,
// subNVuePagePath +
// '.nvue') + '?entry'
// }
}
})
}
} else {
page.style && (delete page.style.subNVues)
}
if (isNVuePage(page, root)) {
// 存储 nvue 相关信息
pagePath = normalizePath(path.join(root, pagePath))
// if (process.env.UNI_USING_NVUE_COMPILER) {
process.UNI_NVUE_ENTRY[pagePath] = getNVueMainJsPath(pagePath)
// } else {
// process.UNI_NVUE_ENTRY[pagePath] = path.resolve(process.env.UNI_INPUT_DIR, pagePath + '.nvue') + '?entry'
// }
uniNVuePages[pagePath + '.html'] = {
'window': page.style || {}
}
return false
}
return true
}
function getMainJsPath (page) {
return path.resolve(process.env.UNI_INPUT_DIR, getMainEntry() + '?' + JSON.stringify({
page: encodeURIComponent(page)
}))
}
function getNVueMainJsPath (page) {
return path.resolve(process.env.UNI_INPUT_DIR, getNVueMainEntry() + '?' + JSON.stringify({
page: encodeURIComponent(page)
}))
}
process.UNI_ENTRY = {}
process.UNI_NVUE_ENTRY = {}
let uniNVuePages = {}
function parsePages (pagesJson, pageCallback, subPageCallback) {
if (!pagesJson) {
pagesJson = getPagesJson()
}
// pages
pagesJson.pages.forEach(page => {
pageCallback && pageCallback(page)
})
// subPackages
if (Array.isArray(pagesJson.subPackages) && pagesJson.subPackages.length) {
pagesJson.subPackages.forEach((subPackage) => {
const {
root,
pages
} = subPackage
pages.forEach(page => {
root && subPageCallback && subPageCallback(root, page, subPackage)
})
})
}
}
function parseEntry (pagesJson) {
process.UNI_ENTRY = {
'common/main': path.resolve(process.env.UNI_INPUT_DIR, getMainEntry())
}
process.UNI_SUB_PACKAGES_ROOT = {}
process.UNI_NVUE_ENTRY = {}
if (process.env.UNI_USING_NATIVE) {
// TODO 考虑 pages.json.js
process.UNI_NVUE_ENTRY['app-config'] = path.resolve(process.env.UNI_INPUT_DIR, 'pages.json')
process.UNI_NVUE_ENTRY['app-service'] = path.resolve(process.env.UNI_INPUT_DIR, getMainEntry())
}
uniNVuePages = {}
if (!pagesJson) {
pagesJson = getPagesJson() // 会检测修改 nvue entry
}
// pages
pagesJson.pages.forEach(page => {
process.UNI_ENTRY[page.path] = getMainJsPath(page.path)
})
// subPackages
if (Array.isArray(pagesJson.subPackages) && pagesJson.subPackages.length) {
pagesJson.subPackages.forEach(({
root,
pages
}) => {
Array.isArray(pages) && pages.forEach(page => {
if (root) {
const pagePath = normalizePath(path.join(root, page.path))
process.UNI_ENTRY[pagePath] = getMainJsPath(pagePath)
process.UNI_SUB_PACKAGES_ROOT[pagePath] = root
}
})
})
}
}
module.exports = {
getMainEntry,
getNVueMainEntry,
parsePages,
parseEntry,
getPagesJson,
parsePagesJson
}
const fs = require('fs')
const path = require('path')
const {
normalizePath
} = require('./util')
const {
SCSS,
SASS
} = require('./scss')
const uniRuntime = '@dcloudio/vue-cli-plugin-uni/packages/mp-vue'
const mpvueRuntime = '@dcloudio/vue-cli-plugin-uni/packages/mpvue'
const megaloRuntime = '@dcloudio/vue-cli-plugin-uni/packages/megalo'
const uniCompiler = '@dcloudio/uni-template-compiler'
const mpvueCompiler = '@dcloudio/vue-cli-plugin-uni/packages/mpvue-template-compiler'
const megaloCompiler = '@megalo/template-compiler'
function getShadowCss () {
let tagName = 'page'
if (process.env.UNI_PLATFORM === 'h5') {
tagName = 'body'
}
return `${tagName}::after{position:fixed;content:'';left:-1000px;top:-1000px;-webkit-animation:shadow-preload .1s;-webkit-animation-delay:3s;animation:shadow-preload .1s;animation-delay:3s}@-webkit-keyframes shadow-preload{0%{background-image:url(https://cdn.dcloud.net.cn/img/shadow-grey.png)}100%{background-image:url(https://cdn.dcloud.net.cn/img/shadow-grey.png)}}@keyframes shadow-preload{0%{background-image:url(https://cdn.dcloud.net.cn/img/shadow-grey.png)}100%{background-image:url(https://cdn.dcloud.net.cn/img/shadow-grey.png)}}`
}
function getCopyOption (file, options) {
const from = path.resolve(process.env.UNI_INPUT_DIR, file)
if (fs.existsSync(from)) {
return Object.assign({
from,
to: path.resolve(process.env.UNI_OUTPUT_DIR, file)
}, options)
}
}
function getCopyOptions (files, options = {}, subPackages = true) {
const copyOptions = []
files.forEach(file => {
// 主包
const copyOption = getCopyOption(file, options)
if (copyOption) {
copyOptions.push(copyOption)
}
if (subPackages) {
// 分包
Object.keys(process.UNI_SUBPACKAGES).forEach(root => { // 分包静态资源
const subCopyOption = getCopyOption(path.join(root, file), options)
if (subCopyOption) {
copyOptions.push(subCopyOption)
}
})
}
})
return copyOptions
}
function getStaticCopyOptions (assetsDir) {
const ignore = []
Object.keys(PLATFORMS).forEach(platform => {
if (process.env.UNI_PLATFORM !== platform) {
ignore.push(platform + '/**/*')
}
})
return getCopyOptions(
[assetsDir], {
ignore
}
)
}
const PLATFORMS = {
'h5': {
global: '',
exts: false,
vue: '@dcloudio/vue-cli-plugin-uni/packages/h5-vue',
compiler: false,
megalo: false,
subPackages: false,
cssVars: {
'--status-bar-height': '0px'
},
copyWebpackOptions ({
assetsDir
}) {
return [
...getStaticCopyOptions(assetsDir),
{
from: require.resolve('@dcloudio/uni-h5/dist/index.css'),
to: assetsDir,
transform (content) {
if (process.env.NODE_ENV === 'production') {
return content + getShadowCss()
}
return content
}
},
...getCopyOptions(['hybrid/html'])
]
}
},
'app-plus': {
global: 'wx',
exts: {
style: '.wxss',
template: '.wxml'
},
vue: mpvueRuntime,
compiler: mpvueCompiler,
megalo: false,
subPackages: false,
cssVars: {
'--window-top': '0px',
'--window-bottom': '0px'
},
copyWebpackOptions ({
assetsDir
}) {
const files = ['hybrid/html']
if (!process.env.UNI_USING_NATIVE) {
files.push('wxcomponents')
}
return [
...getStaticCopyOptions(assetsDir),
...getCopyOptions(files)
]
}
},
'mp-qq': {
global: 'wx',
exts: {
style: '.qss',
template: '.qml'
},
vue: mpvueRuntime,
compiler: mpvueCompiler,
megalo: false,
subPackages: true,
cssVars: {
'--status-bar-height': '25px',
'--window-top': '0px',
'--window-bottom': '0px'
},
project: 'project.config.json',
copyWebpackOptions ({
assetsDir
}) {
return [
...getStaticCopyOptions(assetsDir),
...getCopyOptions(['wxcomponents'])
]
}
},
'mp-weixin': {
global: 'wx',
exts: {
style: '.wxss',
template: '.wxml'
},
vue: mpvueRuntime,
compiler: mpvueCompiler,
megalo: false,
subPackages: true,
cssVars: {
'--status-bar-height': '25px',
'--window-top': '0px',
'--window-bottom': '0px'
},
project: 'project.config.json',
copyWebpackOptions ({
assetsDir,
manifestPlatformOptions
}) {
const files = [
'sitemap.json',
'ext.json',
'custom-tab-bar'
]
if (manifestPlatformOptions.workers) {
files.push(manifestPlatformOptions.workers)
}
return [
...getStaticCopyOptions(assetsDir),
...getCopyOptions(['wxcomponents']),
...getCopyOptions(files, {}, false)
]
}
},
'mp-baidu': {
global: 'swan',
exts: {
style: '.css',
template: '.swan'
},
vue: megaloRuntime,
compiler: megaloCompiler,
megalo: 'swan',
subPackages: true,
cssVars: {
'--status-bar-height': '25px',
'--window-top': '0px',
'--window-bottom': '0px'
},
project: 'project.swan.json',
copyWebpackOptions ({
assetsDir
}) {
return [
...getStaticCopyOptions(assetsDir),
...getCopyOptions(['swancomponents'])
]
}
},
'mp-alipay': {
global: 'my',
exts: {
style: '.acss',
template: '.axml'
},
vue: megaloRuntime,
compiler: megaloCompiler,
megalo: 'alipay',
subPackages: false,
cssVars: {
'--status-bar-height': '25px',
'--window-top': '0px',
'--window-bottom': '0px'
},
copyWebpackOptions ({
assetsDir
}) {
return [
...getStaticCopyOptions(assetsDir),
...getCopyOptions(['mycomponents'])
]
}
},
'mp-toutiao': {
global: 'tt',
exts: {
style: '.ttss',
template: '.ttml'
},
vue: megaloRuntime,
compiler: megaloCompiler,
megalo: 'tt',
subPackages: false,
cssVars: {
'--status-bar-height': '25px',
'--window-top': '0px',
'--window-bottom': '0px'
},
project: 'project.tt.json',
copyWebpackOptions ({
assetsDir
}) {
return [
...getStaticCopyOptions(assetsDir),
...getCopyOptions(['ttcomponents'])
]
}
}
}
// 解决 vue-cli-service lint 时 UNI_PLATFORM 不存在
process.env.UNI_PLATFORM = process.env.UNI_PLATFORM || 'h5'
const platform = PLATFORMS[process.env.UNI_PLATFORM]
const preprocessContext = {}
Object.keys(PLATFORMS).forEach(platform => {
preprocessContext[platform.toUpperCase()] = false
})
preprocessContext[process.env.UNI_PLATFORM.toUpperCase()] = true
preprocessContext['MP'] = false
preprocessContext['APP'] = false
preprocessContext['APP-PLUS-NVUE'] = false
preprocessContext['APP_PLUS_NVUE'] = false
preprocessContext['APP-VUE'] = false
preprocessContext['APP_VUE'] = false
preprocessContext['APP-NVUE'] = false
preprocessContext['APP_NVUE'] = false
if (process.env.UNI_PLATFORM === 'app-plus') {
preprocessContext['APP-VUE'] = true
preprocessContext['APP_VUE'] = true
}
if (process.env.UNI_PLATFORM.indexOf('mp-') === 0) {
preprocessContext['MP'] = true
}
if (process.env.UNI_PLATFORM.indexOf('app-') === 0) {
preprocessContext['APP'] = true
}
if (process.UNI_SCRIPT_DEFINE && Object.keys(process.UNI_SCRIPT_DEFINE).length) {
Object.keys(process.UNI_SCRIPT_DEFINE).forEach(name => {
preprocessContext[name] = process.UNI_SCRIPT_DEFINE[name]
})
}
Object.keys(preprocessContext).forEach(platform => {
if (platform.indexOf('-') !== -1) {
preprocessContext[platform.replace(/-/g, '_')] = preprocessContext[platform]
}
})
const nvuePreprocessContext = Object.assign({}, preprocessContext, {
'APP-VUE': false,
'APP_VUE': false,
'APP-NVUE': true,
'APP_NVUE': true,
'APP-PLUS-NVUE': true,
'APP_PLUS_NVUE': true
})
const isInHBuilderX = fs.existsSync(path.resolve(process.env.UNI_CLI_CONTEXT, 'bin/uniapp-cli.js'))
let isInHBuilderXAlpha = false
if (isInHBuilderX) {
try {
if (require(path.resolve(process.env.UNI_CLI_CONTEXT, '../about/package.json')).alpha) {
isInHBuilderXAlpha = true
}
} catch (e) {
}
}
let sourceRoot = false
function devtoolModuleFilenameTemplate (info) {
if (!sourceRoot) {
if (isInHBuilderX) {
sourceRoot = normalizePath(process.env.UNI_INPUT_DIR)
} else {
sourceRoot = normalizePath(process.env.UNI_CLI_CONTEXT)
}
}
let filePath = false
const absoluteResourcePath = normalizePath(info.absoluteResourcePath)
if (
absoluteResourcePath.indexOf(sourceRoot) !== -1 &&
(
absoluteResourcePath.endsWith('.js') ||
absoluteResourcePath.endsWith('.ts')
)
) {
filePath = normalizePath(path.relative(sourceRoot, absoluteResourcePath))
if (
filePath.indexOf('node_modules/@dcloudio') === 0 ||
filePath.indexOf('node_modules/vue-loader') === 0 ||
filePath.indexOf('node_modules/webpack') === 0
) {
filePath = false
}
} else if (
!info.moduleId &&
(
absoluteResourcePath.endsWith('.vue') ||
absoluteResourcePath.endsWith('.nvue')
)
) {
if (
absoluteResourcePath.indexOf('src') !== 0 &&
absoluteResourcePath.indexOf('node-modules') !== 0
) {
filePath = normalizePath(path.relative(sourceRoot, absoluteResourcePath))
} else {
filePath = absoluteResourcePath
}
}
if (
filePath &&
filePath !== 'main.js' &&
filePath !== 'main.ts' &&
filePath !== 'src/main.js' &&
filePath !== 'src/main.ts'
) {
return `uni-app:///${filePath}`
}
}
module.exports = {
isInHBuilderX,
isInHBuilderXAlpha,
runByHBuilderX: isInHBuilderX || !!process.env.UNI_HBUILDERX_PLUGINS,
devtoolModuleFilenameTemplate,
getFlexDirection (json) {
let flexDir = 'column'
if (json && json['nvue'] && json['nvue']['flex-direction']) {
flexDir = json['nvue']['flex-direction']
const flexDirs = ['row', 'row-reverse', 'column', 'column-reverse']
if (flexDirs.indexOf(flexDir) === -1) {
flexDir = 'column'
}
}
return flexDir
},
jsPreprocessOptions: {
type: 'js',
context: preprocessContext
},
cssPreprocessOptions: {
type: 'css',
context: preprocessContext
},
htmlPreprocessOptions: {
type: 'html',
context: preprocessContext
},
nvueCssPreprocessOptions: {
type: 'css',
context: nvuePreprocessContext
},
nvueJsPreprocessOptions: {
type: 'js',
context: nvuePreprocessContext
},
nvueHtmlPreprocessOptions: {
type: 'html',
context: nvuePreprocessContext
},
isSupportSubPackages () {
return platform.subPackages
},
getPlatforms () {
return Object.keys(PLATFORMS)
},
getPlatformCopy () {
return platform.copyWebpackOptions
},
getPlatformGlobal () {
return platform.global
},
getPlatformExts () {
return platform.exts
},
getPlatformTarget () {
return platform.megalo
},
getPlatformProject () {
return platform.project
},
getPlatformVue () {
if (process.env.UNI_USING_COMPONENTS) {
return uniRuntime
}
return platform.vue
},
getPlatformCompiler () {
if (process.env.UNI_USING_COMPONENTS || process.env.UNI_PLATFORM === 'h5') {
return require(uniCompiler)
}
return require(platform.compiler)
},
getPlatformCssVars () {
return platform.cssVars
},
getPlatformCssnano () {
return {
calc: false,
orderedValues: false,
mergeLonghand: false,
mergeRules: false,
cssDeclarationSorter: false,
discardComments: false,
discardDuplicates: false // 条件编译会导致重复
}
},
getShadowCss,
getShadowTemplate (colorType = 'grey') {
let tagName = 'cover-image'
if (process.env.UNI_PLATFORM === 'mp-toutiao') {
tagName = 'image'
}
return `<${tagName} src="https://cdn.dcloud.net.cn/img/shadow-${colorType}.png" style="z-index:998;position:fixed;left:0;top:0;width:100%;height:3px;"/>`
},
getPlatformScss () {
return SCSS
},
getPlatformSass () {
return SASS
}
}
const SCSS =
`
$uni-color-primary: #007aff;
$uni-color-success: #4cd964;
$uni-color-warning: #f0ad4e;
$uni-color-error: #dd524d;
$uni-text-color: #333;//基本色
$uni-text-color-inverse: #fff;//反色
$uni-text-color-grey: #999;//辅助灰色,如加载更多的提示信息
$uni-text-color-placeholder: #808080;
$uni-text-color-disable: #c0c0c0;
$uni-bg-color: #ffffff;
$uni-bg-color-grey: #f8f8f8;
$uni-bg-color-hover: #f1f1f1;//点击状态颜色
$uni-bg-color-mask: rgba(0, 0, 0, 0.4);//遮罩颜色
$uni-border-color: #c8c7cc;
$uni-font-size-sm: 24rpx;
$uni-font-size-base: 28rpx;
$uni-font-size-lg: 32rpx;
$uni-img-size-sm: 40rpx;
$uni-img-size-base: 52rpx;
$uni-img-size-lg: 80rpx;
$uni-border-radius-sm: 4rpx;
$uni-border-radius-base: 6rpx;
$uni-border-radius-lg: 12rpx;
$uni-border-radius-circle: 50%;
$uni-spacing-row-sm: 10px;
$uni-spacing-row-base: 20rpx;
$uni-spacing-row-lg: 30rpx;
$uni-spacing-col-sm: 8rpx;
$uni-spacing-col-base: 16rpx;
$uni-spacing-col-lg: 24rpx;
$uni-opacity-disabled: 0.3; // 组件禁用态的透明度
$uni-color-title: #2C405A; // 文章标题颜色
$uni-font-size-title: 40rpx;
$uni-color-subtitle: #555555; // 二级标题颜色
$uni-font-size-subtitle: 36rpx;
$uni-color-paragraph: #3F536E; // 文章段落颜色
$uni-font-size-paragraph: 30rpx;
`
const SASS =
`
$uni-color-primary: #007aff
$uni-color-success: #4cd964
$uni-color-warning: #f0ad4e
$uni-color-error: #dd524d
$uni-text-color: #333//基本色
$uni-text-color-inverse: #fff//反色
$uni-text-color-grey: #999//辅助灰色,如加载更多的提示信息
$uni-text-color-placeholder: #808080
$uni-text-color-disable: #c0c0c0
$uni-bg-color: #ffffff
$uni-bg-color-grey: #f8f8f8
$uni-bg-color-hover: #f1f1f1//点击状态颜色
$uni-bg-color-mask: rgba(0, 0, 0, 0.4)//遮罩颜色
$uni-border-color: #c8c7cc
$uni-font-size-sm: 24rpx
$uni-font-size-base: 28rpx
$uni-font-size-lg: 32rpx
$uni-img-size-sm: 40rpx
$uni-img-size-base: 52rpx
$uni-img-size-lg: 80rpx
$uni-border-radius-sm: 4rpx
$uni-border-radius-base: 6rpx
$uni-border-radius-lg: 12rpx
$uni-border-radius-circle: 50%
$uni-spacing-row-sm: 10px
$uni-spacing-row-base: 20rpx
$uni-spacing-row-lg: 30rpx
$uni-spacing-col-sm: 8rpx
$uni-spacing-col-base: 16rpx
$uni-spacing-col-lg: 24rpx
$uni-opacity-disabled: 0.3 // 组件禁用态的透明度
$uni-color-title: #2C405A // 文章标题颜色
$uni-font-size-title: 40rpx
$uni-color-subtitle: #555555 // 二级标题颜色
$uni-font-size-subtitle: 36rpx
$uni-color-paragraph: #3F536E // 文章段落颜色
$uni-font-size-paragraph: 30rpx
`
module.exports = {
SCSS,
SASS
}
module.exports = {
'resize-sensor': ['h5'],
'ad': ['mp-weixin'],
'audio': ['app-plus', 'mp-weixin', 'h5'],
'button': ['app-plus', 'mp-weixin', 'h5'],
'camera': ['mp-weixin'],
'canvas': ['app-plus', 'mp-weixin'],
'checkbox': ['app-plus', 'mp-weixin', 'h5'],
'checkbox-group': ['app-plus', 'mp-weixin', 'h5'],
'cover-image': ['app-plus', 'mp-weixin'],
'cover-view': ['app-plus', 'mp-weixin'],
'form': ['app-plus', 'mp-weixin', 'h5'],
'functional-page-navigator': ['mp-weixin'],
'icon': ['app-plus', 'mp-weixin'],
'image': ['app-plus', 'mp-weixin', 'h5'],
'input': ['app-plus', 'mp-weixin', 'h5'],
'label': ['app-plus', 'mp-weixin', 'h5'],
'live-player': ['mp-weixin'],
'live-pusher': ['mp-weixin'],
'map': ['app-plus', 'mp-weixin', 'h5'],
'movable-area': ['app-plus', 'mp-weixin'],
'movable-view': ['app-plus', 'mp-weixin'],
'navigator': ['app-plus', 'mp-weixin', 'h5'],
'official-account': ['mp-weixin'],
'open-data': ['mp-weixin'],
'picker': ['app-plus', 'mp-weixin', 'h5'],
'picker-view': ['app-plus', 'mp-weixin', 'h5'],
'picker-view-column': ['app-plus', 'mp-weixin', 'h5'],
'progress': ['app-plus', 'mp-weixin', 'h5'],
'radio': ['app-plus', 'mp-weixin', 'h5'],
'radio-group': ['app-plus', 'mp-weixin', 'h5'],
'rich-text': ['app-plus', 'mp-weixin', 'h5'],
'scroll-view': ['app-plus', 'mp-weixin', 'h5'],
'slider': ['app-plus', 'mp-weixin', 'h5'],
'swiper': ['app-plus', 'mp-weixin', 'h5'],
'swiper-item': ['app-plus', 'mp-weixin', 'h5'],
'switch': ['app-plus', 'mp-weixin', 'h5'],
'text': ['app-plus', 'mp-weixin', 'h5'],
'textarea': ['app-plus', 'mp-weixin', 'h5'],
'video': ['app-plus', 'mp-weixin', 'h5'],
'view': ['app-plus', 'mp-weixin', 'h5'],
'web-view': ['app-plus', 'mp-weixin']
}
const path = require('path')
const hash = require('hash-sum')
const crypto = require('crypto')
const PLATFORMS = [
'h5',
'app-plus',
'mp-qq',
'mp-weixin',
'mp-baidu',
'mp-alipay',
'mp-toutiao',
'quickapp'
]
const isWin = /^win/.test(process.platform)
const normalizePath = path => (isWin ? path.replace(/\\/g, '/') : path)
function removeExt (str, ext) {
if (ext) {
const reg = new RegExp(ext.replace(/\./, '\\.') + '$')
return normalizePath(str.replace(reg, ''))
}
return normalizePath(str.replace(/\.\w+$/g, ''))
}
function hashify (filepath) {
const relativePath = removeExt(path.relative(process.env.UNI_INPUT_DIR, filepath))
return hash(relativePath)
}
function md5 (str) {
const hash = crypto.createHash('md5')
hash.update(str)
return hash.digest('hex')
}
function cached (fn) {
const cache = Object.create(null)
return function cachedFn (str) {
const hit = cache[str]
return hit || (cache[str] = fn(str))
}
}
const camelizeRE = /-(\w)/g
const camelize = cached((str) => {
return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
})
const hyphenateRE = /\B([A-Z])/g
const hyphenate = cached((str) => {
return str.replace(hyphenateRE, '-$1').toLowerCase()
})
const REGEX_PX = /(:|\s|\(|\/)[+-]?\d+(\.\d+)?u?px/g
const REGEX_UPX = /(:|\s|\(|\/)[+-]?\d+(\.\d+)?upx/g
function convertStaticStyle (styleStr) {
if (typeof styleStr === 'string') {
let matches = styleStr.match(REGEX_UPX)
if (matches && matches.length) {
matches.forEach(function (match) {
styleStr = styleStr.replace(match, match.substr(0, match.length - 3) + 'rpx')
})
}
// TODO 不应该再支持 px 转 rpx
if (process.UNI_TRANSFORM_PX) { // 需要转换 px
matches = styleStr.match(REGEX_PX)
if (matches && matches.length) {
matches.forEach(function (match) {
styleStr = styleStr.replace(match, match.substr(0, match.length - 2) + 'rpx')
})
}
}
}
return styleStr
}
function hasModule (name) {
try {
return !!require.resolve(name)
} catch (e) {}
return false
}
module.exports = {
md5,
hasOwn (obj, key) {
return hasOwnProperty.call(obj, key)
},
hasModule,
parseStyle (style = {}) {
Object.keys(style).forEach(name => {
if (PLATFORMS.includes(name)) {
if (name === process.env.UNI_PLATFORM) {
Object.assign(style, style[name] || {})
}
delete style[name]
}
})
return style
},
hashify,
removeExt,
camelize,
hyphenate,
normalizePath,
convertStaticStyle,
getComponentName: cached((str) => {
if (str.indexOf('wx-') === 0) {
return str.replace('wx-', 'weixin-')
}
return str
})
}
{
"name": "@dcloudio/uni-cli-shared",
"version": "0.2.986",
"description": "uni-cli-shared",
"main": "lib/index.js",
"files": [
"lib"
],
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "fxy060608",
"license": "Apache-2.0",
"dependencies": {
"hash-sum": "^1.0.2",
"strip-json-comments": "^2.0.1"
}
}
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
\ No newline at end of file
const compiler = require('../lib')
function assertCodegen (template, templateCode, renderCode = `with(this){}`, options = {}) {
const res = compiler.compile(template, {
resourcePath: 'test.wxml',
mp: Object.assign({
minified: true,
isTest: true,
platform: 'mp-alipay'
}, options)
})
expect(res.template).toBe(templateCode)
expect(res.render).toBe(renderCode)
}
describe('mp:compiler-mp-alipay', () => {
it('generate v-for directive', () => {
assertCodegen(
'<view><view v-for="(item,index) in items" :key="index"></view></view>',
`<view><block a:for="{{items}}" a:for-item="item" a:for-index="index" a:key="index"><view></view></block></view>`
)
})
it('generate v-else-if with v-else directive', () => {
assertCodegen(
'<view><view v-if="show">hello</view><view v-else-if="hide">world</view><view v-else>bye</view></view>',
`<view><block a:if="{{show}}"><view>hello</view></block><block a:else><block a:if="{{hide}}"><view>world</view></block><block a:else><view>bye</view></block></block></view>`
)
})
it('generate ref', () => {
assertCodegen(
'<component1 ref="c1">text</component1>',
`<component1 vue-id="1" ref="__r" data-ref="c1" onVueInit="__l">text</component1>`
)
assertCodegen(
'<component1 :ref="c2">text<text>123213</text></component1>',
`<component1 vue-id="1" ref="__r" data-ref="{{c2}}" onVueInit="__l">text<text>123213</text></component1>`
)
assertCodegen(
'<component1 v-for="item in items" ref="c3"></component1>',
`<block a:for="{{items}}" a:for-item="item" a:for-index="__i0__"><component1 vue-id="{{'1-'+__i0__}}" ref="__r" data-ref-in-for="c3" onVueInit="__l"></component1></block>`
)
assertCodegen(
'<component1 v-for="item in items" :ref="c4"></component1>',
`<block a:for="{{items}}" a:for-item="item" a:for-index="__i0__"><component1 vue-id="{{'1-'+__i0__}}" ref="__r" data-ref-in-for="{{c4}}" onVueInit="__l"></component1></block>`
)
})
it('generate default slot', () => {
assertCodegen(
'<component1>text</component1>',
`<component1 vue-id="1" onVueInit="__l">text</component1>`
)
assertCodegen(
'<component1>text<text>123213</text></component1>',
`<component1 vue-id="1" onVueInit="__l">text<text>123213</text></component1>`
)
assertCodegen(
'<component1>text<block slot="right"></block></component1>',
`<component1 vue-id="1" onVueInit="__l">text<view slot="right"></view></component1>`
)
})
it('generate class binding', () => {
assertCodegen(
'<div :class="{ active: isActive }">1</div>',
`<view class="{{(('_div')+' '+((isActive)?'active':''))}}">1</view>`
)
assertCodegen(
`<p class="static" :class="{ active: isActive, 'text-danger': hasError }">2</p>`,
`<view class="{{((('static _p')+' '+((isActive)?'active':''))+' '+((hasError)?'text-danger':''))}}">2</view>`
)
assertCodegen(
'<p class="static" :class="[activeClass, errorClass]">3</p>',
`<view class="{{((('static _p')+' '+activeClass)+' '+errorClass)}}">3</view>`
)
assertCodegen(
`<p class="static" :class="[isActive ? activeClass : '', errorClass]">4</p>`,
`<view class="{{((('static _p')+' '+(isActive?activeClass:''))+' '+errorClass)}}">4</view>`
)
assertCodegen(
`<p class="static" :class="[{ active: isActive }, errorClass]">5</p>`,
`<view class="{{((('static _p')+' '+[(isActive)?'active':''])+' '+errorClass)}}">5</view>`
)
assertCodegen(
`<div class="container" :class="computedClassObject">6</div>`,
`<view class="{{(('container _div')+' '+computedClassObject)}}">6</view>`
)
// assertCodegen(
// `<div class="container" :class="computedClassObject">6</div>`,
// `<view class="{{$root.c0}}">6</view>`,
// `with(this){var c0=__get_class(computedClassObject,"container");$mp.data=Object.assign({},{$root:{c0:c0}})}`
// )
assertCodegen(
`<p :class="index === currentIndex ? activeClass : itemClass">7</p>`,
`<view class="{{(('_p')+' '+(index===currentIndex?activeClass:itemClass))}}">7</view>`
)
assertCodegen(
`<p :class="'m-content-head-'+message.user">8</p>`,
`<view class="{{(('_p')+' '+('m-content-head-'+message.user))}}">8</view>`
)
assertCodegen(
`<p :class="classStr1 || classStr2" class="bg">9</p>`,
`<view class="{{(('bg _p')+' '+(classStr1||classStr2))}}">9</view>`
)
})
it('generate events with v-on directive', () => {
assertCodegen(
`<uni-list-item title="标题文字" note="描述信息" show-extra-icon="true" :extra-icon="{color: '#4cd964',size: '22',type: 'spinner'}"></uni-list-item>`,
`<uni-list-item vue-id="1" title="标题文字" note="描述信息" show-extra-icon="true" extra-icon="{{$root.a0}}" onVueInit="__l"></uni-list-item>`,
`with(this){var a0={color:"#4cd964",size:"22",type:"spinner"};$mp.data=Object.assign({},{$root:{a0:a0}})}`
)
assertCodegen(
`<view @click="onClick" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd" @touchcancel="onTouchCancel" @longtap="onLongTap" @longpress="onLongPress"></view>`,
`<view data-event-opts="{{[['tap',[['onClick',['$event']]]],['touchStart',[['onTouchStart',['$event']]]],['touchMove',[['onTouchMove',['$event']]]],['touchEnd',[['onTouchEnd',['$event']]]],['touchCancel',[['onTouchCancel',['$event']]]],['longTap',[['onLongTap',['$event']]]],['longTap',[['onLongPress',['$event']]]]]}}" onTap="__e" onTouchStart="__e" onTouchMove="__e" onTouchEnd="__e" onTouchCancel="__e" onLongTap="__e"></view>`
)
assertCodegen(
`<form @submit="formSubmit" @reset="formReset"/>`,
`<form data-event-opts="{{[['submit',[['formSubmit',['$event']]]]]}}" onSubmit="__e" onReset="formReset"></form>`
)
assertCodegen(
`<map @callouttap="calloutTap" @controltap="controlTap" @markertap="markerTap" @regionchange="regionChange" @tap="tap"/>`,
`<map data-event-opts="{{[['tap',[['tap',['$event']]]]]}}" onCalloutTap="calloutTap" onControlTap="controlTap" onMarkerTap="markerTap" onRegionChange="regionChange" onTap="__e"></map>`
)
assertCodegen(
`<view @transitionend="transitionEnd" @animationstart="animationStart" @animationiteration="animationIteration" @animationend="animationEnd" @firstappear="firstAppear"/>`,
`<view data-event-opts="{{[['transitionEnd',[['transitionEnd',['$event']]]],['animationStart',[['animationStart',['$event']]]],['animationIteration',[['animationIteration',['$event']]]],['animationEnd',[['animationEnd',['$event']]]],['firstAppear',[['firstAppear',['$event']]]]]}}" onTransitionEnd="__e" onAnimationStart="__e" onAnimationIteration="__e" onAnimationEnd="__e" onFirstAppear="__e"></view>`
)
assertCodegen(
`<scroll-view @scrolltoupper="scrollToUpper" @scrolltolower="scrollToLower"/>`,
`<scroll-view data-event-opts="{{[['scrollToUpper',[['scrollToUpper',['$event']]]],['scrollToLower',[['scrollToLower',['$event']]]]]}}" onScrollToUpper="__e" onScrollToLower="__e"></scroll-view>`
)
assertCodegen(
`<movable-view @changeend="changeEnd"/>`,
`<movable-view data-event-opts="{{[['changeEnd',[['changeEnd',['$event']]]]]}}" onChangeEnd="__e"></movable-view>`
)
})
})
const compiler = require('../lib')
function assertCodegen (template, templateCode, renderCode = `with(this){}`, options = {}) {
const res = compiler.compile(template, {
resourcePath: 'test.wxml',
mp: Object.assign({
minified: true,
isTest: true,
platform: 'mp-baidu'
}, options)
})
expect(res.template).toBe(templateCode)
expect(res.render).toBe(renderCode)
}
describe('mp:compiler-mp-baidu', () => {
it('generate v-for directive', () => {
assertCodegen(
'<view><view v-for="(item,index) in items" :key="index"></view></view>',
`<view><block s-for="{{items}}" s-for-item="item" s-for-index="index" s-key="index"><view></view></block></view>`
)
})
it('generate scoped slot', () => {
assertCodegen(
'<foo><template slot-scope="bar">{{ bar.foo }}</template></foo>',
`<foo vue-id="1" vue-slots="{{['default']}}"><view slot="default">{{foo}}</view></foo>`
)
assertCodegen(
'<foo><view slot-scope="bar">{{ bar.foo }}</view></foo>',
`<foo vue-id="1" vue-slots="{{['default']}}"><view slot="default"><view>{{foo}}</view></view></foo>`
)
})
it('generate named scoped slot', () => {
assertCodegen(
'<foo><template slot="foo" slot-scope="bar">{{ bar.foo }}</template></foo>',
`<foo vue-id="1" vue-slots="{{['foo']}}"><view slot="foo">{{foo}}</view></foo>`
)
assertCodegen(
'<foo><view slot="foo" slot-scope="bar">{{ bar.foo }}</view></foo>',
`<foo vue-id="1" vue-slots="{{['foo']}}"><view slot="foo"><view>{{foo}}</view></view></foo>`
)
})
it('generate scoped slot with multiline v-if', () => {
assertCodegen(
'<foo><template v-if="\nshow\n" slot-scope="bar">{{ bar.foo }}</template></foo>',
`<foo vue-id="1" vue-slots="{{['default']}}"><view slot="default"><block s-if="{{show}}">{{foo}}</block><block s-else><block></block></block></view></foo>`
)
assertCodegen(
'<foo><view v-if="\nshow\n" slot="foo" slot-scope="bar">{{ bar.foo }}</view></foo>',
`<foo vue-id="1" vue-slots="{{['foo']}}"><view slot="foo"><block s-if="{{show}}"><view>{{foo}}</view></block></view></foo>`
)
})
it('generate scoped slot', () => {
assertCodegen(
'<span><slot v-bind:user="user">{{ user.lastName }}</slot></span>',
`<label class="_span"><block s-if="{{$slots.default}}"><slot name="default" var-user="user"></slot></block><block s-else>{{user.lastName}}</block></label>`
)
assertCodegen(
'<span><slot name="header" v-bind:user="user">{{ user.lastName }}</slot></span>',
`<label class="_span"><block s-if="{{$slots.header}}"><slot name="header" var-user="user"></slot></block><block s-else>{{user.lastName}}</block></label>`
)
})
it('generate vue id', () => {
assertCodegen(
'<Test/>',
`<test vue-id="1"></test>`
)
assertCodegen(
'<Test a="a">',
`<test vue-id="1" a="a"></test>`
)
assertCodegen(
'<view><Test v-for="item in items" :key="item"/></view>',
`<view><block s-for="{{items}}" s-for-item="item" s-for-index="__i0__" s-key="*this"><test vue-id="{{'1-'+__i0__}}"></test></block></view>`
)
assertCodegen(
'<view><Test v-for="item in items" :key="item"><Test v-for="item in item.items" :key="item"></Test></Test></view>',
`<view><block s-for="{{items}}" s-for-item="item" s-for-index="__i0__" s-key="*this"><test vue-id="{{'1-'+__i0__}}" vue-slots="{{['default']}}"><block s-for="{{item.items}}" s-for-item="item" s-for-index="__i1__" s-key="*this"><test vue-id="{{('2-'+__i0__+'-'+__i1__)+','+('1-'+__i0__)}}"></test></block></test></block></view>`
)
assertCodegen(
'<view><Test v-for="(item,index) in items" :key="item"><Test v-for="(item,index1) in item.items" :key="item"></Test></Test></view>',
`<view><block s-for="{{items}}" s-for-item="item" s-for-index="index" s-key="*this"><test vue-id="{{'1-'+index}}" vue-slots="{{['default']}}"><block s-for="{{item.items}}" s-for-item="item" s-for-index="index1" s-key="*this"><test vue-id="{{('2-'+index+'-'+index1)+','+('1-'+index)}}"></test></block></test></block></view>`
)
})
it('generate text trim', () => {
assertCodegen(
'<text>\nN: {{title}}\n′</text>',
`<text>{{'N: '+title+"\\\\n′"}}</text>`
)
assertCodegen(
'<text>我是第一行1\n我的第二行</text>',
`<text>我是第一行1\n我的第二行</text>`
)
assertCodegen(
'<text>我是第一行2\n我的第二行1{{title}}</text>',
`<text>{{"我是第一行2\\\\n我的第二行1"+title}}</text>`
)
assertCodegen(
`<text>我是第一行3
我的第二行2{{title}}</text>`,
`<text>{{"我是第一行3\\\\n 我的第二行2"+title}}</text>`
)
})
})
const compiler = require('../lib')
function assertCodegen (template, templateCode, renderCode = `with(this){}`, options = {}) {
const res = compiler.compile(template, {
resourcePath: 'test.wxml',
mp: Object.assign({
minified: true,
isTest: true,
platform: 'mp-qq'
}, options)
})
expect(res.template).toBe(templateCode)
expect(res.render).toBe(renderCode)
}
describe('mp:compiler-mp-qq', () => {
it('generate text trim', () => {
assertCodegen(
'<text>\nN: {{title}}\n′</text>',
`<text>{{'N: '+title+"\\\\n′"}}</text>`
)
assertCodegen(
'<text>我是第一行1\n我的第二行</text>',
`<text>我是第一行1\n我的第二行</text>`
)
assertCodegen(
'<text>我是第一行2\n我的第二行1{{title}}</text>',
`<text>{{"我是第一行2\\\\n我的第二行1"+title}}</text>`
)
assertCodegen(
`<text>我是第一行3
我的第二行2{{title}}</text>`,
`<text>{{"我是第一行3\\\\n 我的第二行2"+title}}</text>`
)
})
})
const compiler = require('../lib')
function assertCodegen (template, templateCode, renderCode = `with(this){}`, options = {}) {
const res = compiler.compile(template, {
resourcePath: 'test.wxml',
mp: Object.assign({
minified: true,
isTest: true,
platform: 'mp-toutiao'
}, options)
})
expect(res.template).toBe(templateCode)
expect(res.render).toBe(renderCode)
}
describe('mp:compiler-mp-toutiao', () => {
it('generate v-for directive', () => {
assertCodegen(
'<view><view v-for="(item,index) in items" :key="index"></view></view>',
`<view><block tt:for="{{items}}" tt:for-item="item" tt:for-index="index" tt:key="index"><view></view></block></view>`
)
})
it('generate ref', () => {
assertCodegen(
'<my-component ref="ref"></my-component>',
`<my-component class="vue-ref" vue-id="1" data-ref="ref" bind:__l="__l"></my-component>`
)
})
it('generate class binding', () => {
assertCodegen(
'<div :class="{ active: isActive }">1</div>',
`<view class="{{(('_div')+' '+((isActive)?'active':''))}}">1</view>`
)
assertCodegen(
`<p class="static" :class="{ active: isActive, 'text-danger': hasError }">2</p>`,
`<view class="{{((('static _p')+' '+((isActive)?'active':''))+' '+((hasError)?'text-danger':''))}}">2</view>`
)
assertCodegen(
'<p class="static" :class="[activeClass, errorClass]">3</p>',
`<view class="{{((('static _p')+' '+activeClass)+' '+errorClass)}}">3</view>`
)
assertCodegen(
`<p class="static" :class="[isActive ? activeClass : '', errorClass]">4</p>`,
`<view class="{{((('static _p')+' '+(isActive?activeClass:''))+' '+errorClass)}}">4</view>`
)
assertCodegen(
`<p class="static" :class="[{ active: isActive }, errorClass]">5</p>`,
`<view class="{{((('static _p')+' '+[(isActive)?'active':''])+' '+errorClass)}}">5</view>`
)
assertCodegen(
`<div class="container" :class="computedClassObject">6</div>`,
`<view class="{{(('container _div')+' '+computedClassObject)}}">6</view>`
)
// assertCodegen(
// `<div class="container" :class="computedClassObject">6</div>`,
// `<view class="{{$root.c0}}">6</view>`,
// `with(this){var c0=__get_class(computedClassObject,"container");$mp.data=Object.assign({},{$root:{c0:c0}})}`
// )
assertCodegen(
`<p :class="index === currentIndex ? activeClass : itemClass">7</p>`,
`<view class="{{(('_p')+' '+(index===currentIndex?activeClass:itemClass))}}">7</view>`
)
assertCodegen(
`<p :class="'m-content-head-'+message.user">8</p>`,
`<view class="{{(('_p')+' '+('m-content-head-'+message.user))}}">8</view>`
)
assertCodegen(
`<p :class="classStr1 || classStr2" class="bg">9</p>`,
`<view class="{{(('bg _p')+' '+(classStr1||classStr2))}}">9</view>`
)
})
})
const compiler = require('../lib')
function assertCodegen (template, templateCode, renderCode = `with(this){}`, options = {}) {
const res = compiler.compile(template, {
resourcePath: 'test.wxml',
mp: Object.assign({
minified: true,
isTest: true,
platform: 'mp-weixin'
}, options)
})
expect(res.template).toBe(templateCode)
if (typeof renderCode === 'function') {
renderCode(res)
} else {
expect(res.render).toBe(renderCode)
}
}
describe('mp:compiler-mp-weixin', () => {
it('generate scoped slot', () => {
assertCodegen(
'<foo><template slot-scope="{bar}">{{ bar.foo }}</template></foo>',
`<foo generic:scoped-slots-default="test-foo-default" vue-id="1" bind:__l="__l" vue-slots="{{['default']}}"></foo>`,
function (res) {
expect(res.generic[0]).toBe('test-foo-default')
}
)
assertCodegen(
'<foo><view slot-scope="{bar}">{{ bar.foo }}</view></foo>',
`<foo generic:scoped-slots-default="test-foo-default" vue-id="1" bind:__l="__l" vue-slots="{{['default']}}"></foo>`,
function (res) {
expect(res.generic[0]).toBe('test-foo-default')
}
)
})
it('generate named scoped slot', () => {
assertCodegen(
'<foo><template slot="foo" slot-scope="{bar}">{{ bar.foo }}</template></foo>',
`<foo generic:scoped-slots-foo="test-foo-foo" vue-id="1" bind:__l="__l" vue-slots="{{['foo']}}"></foo>`,
function (res) {
expect(res.generic[0]).toBe('test-foo-foo')
}
)
assertCodegen(
'<foo><view slot="foo" slot-scope="{bar}">{{ bar.foo }}</view></foo>',
`<foo generic:scoped-slots-foo="test-foo-foo" vue-id="1" bind:__l="__l" vue-slots="{{['foo']}}"></foo>`,
function (res) {
expect(res.generic[0]).toBe('test-foo-foo')
}
)
})
it('generate scoped slot with multiline v-if', () => {
assertCodegen(
'<foo><template v-if="\nshow\n" slot-scope="{bar}">{{ bar.foo }}</template></foo>',
`<foo generic:scoped-slots-default="test-foo-default" vue-id="1" bind:__l="__l" vue-slots="{{['default']}}"></foo>`,
function (res) {
expect(res.generic[0]).toBe('test-foo-default')
}
)
assertCodegen(
'<foo><view v-if="\nshow\n" slot="foo" slot-scope="{bar}">{{ bar.foo }}</view></foo>',
`<foo generic:scoped-slots-foo="test-foo-foo" vue-id="1" bind:__l="__l" vue-slots="{{['foo']}}"></foo>`,
function (res) {
expect(res.generic[0]).toBe('test-foo-foo')
}
)
})
it('generate scoped slot', () => {
assertCodegen(// TODO vue-id
'<span><slot v-bind:user="user">{{ user.lastName }}</slot></span>',
`<label class="_span"><block wx:if="{{$slots.default}}"><scoped-slots-default user="{{user}}" bind:__l="__l"></scoped-slots-default></block><block wx:else>{{user.lastName}}</block></label>`,
function (res) {
expect(res.componentGenerics['scoped-slots-default']).toBe(true)
}
)
assertCodegen(
'<span><slot name="header" v-bind:user="user">{{ user.lastName }}</slot></span>',
`<label class="_span"><block wx:if="{{$slots.header}}"><scoped-slots-header user="{{user}}" bind:__l="__l"></scoped-slots-header></block><block wx:else>{{user.lastName}}</block></label>`,
function (res) {
expect(res.componentGenerics['scoped-slots-header']).toBe(true)
}
)
})
})
var range = 2
function generateCodeFrame (
source,
start,
end
) {
source = source.replace(/\r\n/g, '\n') // 替换\r\n 为 \n
if (start === void 0) start = 0
if (end === void 0) end = source.length
var lines = source.split(/\n/) // 替换\r?\n 为 \n,不然 length 对不上,导致死循环
var count = 0
var res = []
for (var i = 0; i < lines.length; i++) {
count += lines[i].length + 1
if (count >= start) {
for (var j = i - range; j <= i + range || end > count; j++) {
if (j < 0 || j >= lines.length) {
continue
}
res.push(('' + (j + 1) + (repeat$1(' ', 3 - String(j + 1).length)) + '| ' + (lines[j])))
var lineLength = lines[j].length
if (j === i) {
// push underline
var pad = start - (count - lineLength) + 1
var length = end > count ? lineLength - pad : end - start
res.push(' | ' + repeat$1(' ', pad) + repeat$1('^', length))
} else if (j > i) {
if (end > count) {
var length$1 = Math.min(end - count, lineLength)
res.push(' | ' + repeat$1('^', length$1))
}
count += lineLength + 1
}
}
break
}
}
return res.join('\n')
}
function repeat$1 (str, n) {
var result = ''
if (n > 0) {
while (true) { // eslint-disable-line
if (n & 1) {
result += str
}
n >>>= 1
if (n <= 0) {
break
}
str += str
}
}
return result
}
module.exports = generateCodeFrame
const METHOD_CREATE_ELEMENT = '_c' // createElement
const METHOD_MARK_ONCE = '_o' // markOnce
const METHOD_TO_NUMBER = '_n' // toNumber
const METHOD_TO_STRING = '_s' // toString
const METHOD_RENDER_LIST = '_l' // renderList
const METHOD_RENDER_SLOT = '_t' // renderSlot
const METHOD_LOOSE_EQUAL = '_q' // looseEqual
const METHOD_LOOSE_INDEX_OF = '_i' // looseIndexOf
const METHOD_RENDER_STATIC = '_m' // renderStatic
const METHOD_RESOLVE_FILTER = '_f' // resolveFilter
const METHOD_CHECK_KEY_CODES = '_k' // checkKeyCodes
const METHOD_BIND_OBJECT_PROPS = '_b' // bindObjectProps
const METHOD_CREATE_TEXT_VNODE = '_v' // createTextVNode
const METHOD_CREATE_EMPTY_VNODE = '_e' // createEmptyVNode
const METHOD_RESOLVE_SCOPED_SLOTS = '_u' // resolveScopedSlots
const METHOD_BIND_OBJECT_LISTENERS = '_g' // bindObjectListeners
const METHOD_BIND_DYNAMIC_KEYS = '_d' // bindDynamicKeys
const METHOD_PREPEND_MODIFIER = '_p' // prependModifier
const METHOD_SET = '$set' // $set
const INTERNAL_SET_MODEL = '__set_model'
const INTERNAL_SET_SYNC = '__set_sync'
const INTERNAL_GET_ORIG = '__get_orig'
const INTERNAL_GET_CLASS = '__get_class'
const INTERNAL_GET_STYLE = '__get_style'
const INTERNAL_GET_EVENT = '__get_event'
const INTERNAL_GET_REFS = '__get_refs'
const INTERNAL_EVENT_PROXY = '__e'
const INTERNAL_EVENT_LINK = '__l'
const ALLOWED_GLOBAL_OBJECT = [
'Math',
'Number',
'Date',
'Array',
'Object',
'Boolean',
'String',
'RegExp',
'Map',
'Set',
'JSON',
'Intl',
'console'
]
module.exports = {
SELF_CLOSING_TAGS: ['input'], // 百度需要自闭合
VUE_EVENT_MODIFIERS: {
capture: '!',
once: '~',
passive: '&',
custom: '^'
},
ALLOWED_GLOBAL_OBJECT,
CLASS_REF: 'vue-ref',
CLASS_REF_IN_FOR: 'vue-ref-in-for',
VAR_MP: '$mp',
VAR_ROOT: '$root',
VAR_ORIGINAL: '$orig',
VAR_FILTER: 'F',
ATTR_DATA_EVENT_OPTS: 'data-event-opts',
ATTR_DATA_COM_TYPE: 'data-com-type',
INTERNAL_GET_ORIG,
INTERNAL_GET_CLASS,
INTERNAL_GET_STYLE,
INTERNAL_GET_EVENT,
INTERNAL_GET_REFS,
INTERNAL_EVENT_PROXY,
INTERNAL_EVENT_LINK,
INTERNAL_SET_MODEL,
INTERNAL_SET_SYNC,
METHOD_BUILT_IN: [
METHOD_SET,
INTERNAL_SET_MODEL,
INTERNAL_SET_SYNC,
INTERNAL_GET_ORIG,
INTERNAL_GET_CLASS,
INTERNAL_GET_STYLE,
INTERNAL_GET_EVENT,
INTERNAL_GET_REFS,
INTERNAL_EVENT_PROXY,
METHOD_CREATE_ELEMENT, // createElement
METHOD_MARK_ONCE, // markOnce
METHOD_TO_NUMBER, // toNumber
METHOD_TO_STRING, // toString
METHOD_RENDER_LIST, // renderList
METHOD_RENDER_SLOT, // renderSlot
METHOD_LOOSE_EQUAL, // looseEqual
METHOD_LOOSE_INDEX_OF, // looseIndexOf
METHOD_RENDER_STATIC, // renderStatic
METHOD_RESOLVE_FILTER, // resolveFilter
METHOD_CHECK_KEY_CODES, // checkKeyCodes
METHOD_BIND_OBJECT_PROPS, // bindObjectProps
METHOD_CREATE_TEXT_VNODE, // createTextVNode
METHOD_CREATE_EMPTY_VNODE, // createEmptyVNode
METHOD_RESOLVE_SCOPED_SLOTS, // resolveScopedSlots
METHOD_BIND_OBJECT_LISTENERS, // bindObjectListeners
METHOD_BIND_DYNAMIC_KEYS, // bindDynamicKeys
METHOD_PREPEND_MODIFIER // prependModifier
],
METHOD_CREATE_ELEMENT,
METHOD_TO_STRING,
METHOD_RENDER_LIST,
METHOD_RESOLVE_FILTER,
PREFIX_GLOBAL: 'g',
PREFIX_ATTR: 'a',
PREFIX_METHOD: 'm',
PREFIX_FILTER: 'f',
PREFIX_FOR: 'l',
PREFIX_CLASS: 'c',
PREFIX_STYLE: 's',
PREFIX_EVENT: 'e',
IDENTIFIER_FOR: '__$$for$$__',
IDENTIFIER_ATTR: '__$$attr$$__',
IDENTIFIER_METHOD: '__$$method$$__',
IDENTIFIER_FILTER: '__$$filter$$__',
IDENTIFIER_CLASS: '__$$class$$__',
IDENTIFIER_STYLE: '__$$style$$__',
IDENTIFIER_EVENT: '__$$event$$__',
IDENTIFIER_GLOBAL: '__$$global$$__'
}
const t = require('@babel/types')
const babelTraverse = require('@babel/traverse').default
const {
METHOD_RENDER_LIST
} = require('../constants')
function getDataPath (identifier, parent, scope) {
if (
!(t.isCallExpression(parent)) &&
// not id of a Declaration
!(t.isDeclaration(parent) && parent.id === identifier) &&
// not a params of a function
!(t.isFunction(parent) && parent.params.indexOf(identifier) > -1) &&
// not a key of Property
!(parent.type === 'ObjectProperty' && parent.key === identifier && !parent.computed) &&
// not in an Array destructure pattern
!(parent.type === 'ArrayPattern') &&
// not in an Object destructure pattern
!(parent.parent && parent.parent.type === 'ObjectPattern') &&
// not already in scope
!scope.hasBinding(identifier.name)
) {
return identifier.name
}
}
function getDataPathByMemberExpression (node, ret) {
if (t.isMemberExpression(node.object)) {
getDataPathByMemberExpression(node.object, ret)
} else if (t.isIdentifier(node.object)) {
ret.push(node.object.name)
}
ret.push(node.property.name || node.property.value)
}
const visitor = {
Identifier (path) {
const dataPath = getDataPath(path.node, path.parent, path.scope)
if (dataPath) {
console.log('....identifier', dataPath)
} else {
// console.log('....ignore', path.node.name)
}
},
MemberExpression (path) {
const dataPathArray = []
getDataPathByMemberExpression(path.node, dataPathArray)
path.skip()
},
CallExpression (path) {
const callee = path.node.callee
if (callee.name === METHOD_RENDER_LIST) {
// for
// path.skip()
}
}
}
module.exports = function traverse (ast, state) {
const data = Object.create(null)
babelTraverse(ast, visitor, undefined, {
data
})
}
const TAGS = {
br: 'view',
hr: 'view',
p: 'view',
h1: 'view',
h2: 'view',
h3: 'view',
h4: 'view',
h5: 'view',
h6: 'view',
abbr: 'view',
address: 'view',
b: 'view',
bdi: 'view',
bdo: 'view',
blockquote: 'view',
cite: 'view',
code: 'view',
del: 'view',
ins: 'view',
dfn: 'view',
em: 'view',
strong: 'view',
samp: 'view',
kbd: 'view',
var: 'view',
i: 'view',
mark: 'view',
pre: 'view',
q: 'view',
ruby: 'view',
rp: 'view',
rt: 'view',
s: 'view',
small: 'view',
sub: 'view',
sup: 'view',
time: 'view',
u: 'view',
wbr: 'view',
// 表单元素
// form: 'form',
// input: 'input',
// textarea: 'textarea',
// button: 'button',
select: 'picker',
option: 'view',
optgroup: 'view',
// label: 'label',
fieldset: 'view',
datalist: 'picker',
legend: 'view',
output: 'view',
// 框架
iframe: 'view',
// 图像
img: 'image',
// canvas: 'canvas',
figure: 'view',
figcaption: 'view',
// 音视频
// audio: 'audio',
source: 'audio',
// video: 'video',
track: 'video',
// 链接
a: 'navigator',
nav: 'view',
link: 'navigator',
// 列表
ul: 'view',
ol: 'view',
li: 'view',
dl: 'view',
dt: 'view',
dd: 'view',
menu: 'view',
command: 'view',
// 表格table
table: 'view',
caption: 'view',
th: 'view',
td: 'view',
tr: 'view',
thead: 'view',
tbody: 'view',
tfoot: 'view',
col: 'view',
colgroup: 'view',
// 样式 节
div: 'view',
main: 'view',
span: 'label',
header: 'view',
footer: 'view',
section: 'view',
article: 'view',
aside: 'view',
details: 'view',
dialog: 'view',
summary: 'view',
// progress: 'progress',
meter: 'progress', // todo
head: 'view', // todo
meta: 'view', // todo
base: 'text', // todo
// 'map': 'image', // TODO不是很恰当
area: 'navigator', // j结合map使用
script: 'view',
noscript: 'view',
embed: 'view',
object: 'view',
param: 'view'
}
module.exports = {
getTagName (tagName) {
return TAGS[tagName] || tagName
}
}
const path = require('path')
const parser = require('@babel/parser')
const {
parseComponent,
compile,
compileToFunctions,
ssrCompile,
ssrCompileToFunctions
} = require('vue-template-compiler')
const platforms = require('./platforms')
const traverseScript = require('./script/traverse')
const generateScript = require('./script/generate')
const traverseTemplate = require('./template/traverse')
const generateTemplate = require('./template/generate')
const compilerModule = require('./module')
const generateCodeFrame = require('./codeframe')
module.exports = {
compile (source, options = {}) {
if (!options.mp) { // h5
return compile(source, options)
}
(options.modules || (options.modules = [])).push(compilerModule)
const res = compile(source, Object.assign(options, {
optimize: false
}))
options.mp.platform = platforms[options.mp.platform]
options.mp.scopeId = options.scopeId
options.mp.resourcePath = options.resourcePath
options.mp.globalUsingComponents = options.globalUsingComponents || Object.create(null)
// (可用的原生微信小程序组件,global+scoped)
options.mp.wxComponents = options.wxComponents || Object.create(null)
const state = {
ast: {},
script: '',
template: '',
errors: new Set(),
tips: new Set(),
options: options.mp
}
// console.log(`function render(){${res.render}}`)
const ast = parser.parse(`function render(){${res.render}}`)
res.render = generateScript(traverseScript(ast, state), state)
let template = generateTemplate(traverseTemplate(ast, state), state)
res.specialMethods = state.options.specialMethods || new Set()
delete state.options.specialMethods
res.files = state.files || {}
delete state.files
// resolve scoped slots
res.generic = state.generic || []
delete state.generic
// define scoped slots
res.componentGenerics = state.componentGenerics || {}
delete state.componentGenerics
state.errors.forEach(msg => {
res.errors.push({
msg
})
})
const resourcePath = options.resourcePath.replace(path.extname(options.resourcePath), '')
state.tips.forEach(msg => {
console.log(`提示:${msg}
at ${resourcePath}.vue:1`)
})
/**
* TODO
* 方案0.最佳方案是在 loader 中直接 emitFile,但目前 vue template-loader 不好介入,自定义的 compiler 结果又无法顺利返回给 loader
* 方案1.通过 loader 传递 emitFile 来提交生成 wxml,需要一个 template loader 来给自定义 compier 增加 emitFile
* 方案2.缓存 wxml 内容,由 plugin 生成 assets 来提交生成 wxml
* ...暂时使用方案1
*/
if (options.emitFile) {
if (options.updateSpecialMethods) {
options.updateSpecialMethods(resourcePath, [...res.specialMethods])
}
if (
process.UNI_ENTRY[resourcePath] &&
process.env.UNI_PLATFORM !== 'app-plus' &&
process.env.UNI_PLATFORM !== 'h5'
) {
// 检查是否启用 shadow
let colorType = false
const pageJsonStr = options.getJsonFile(resourcePath)
if (pageJsonStr) {
try {
const windowJson = JSON.parse(pageJsonStr)
if (process.env.UNI_PLATFORM === 'mp-alipay') {
colorType = windowJson.allowsBounceVertical === 'NO' &&
windowJson.navigationBarShadow &&
windowJson.navigationBarShadow.colorType
} else {
colorType = windowJson.disableScroll &&
windowJson.navigationBarShadow &&
windowJson.navigationBarShadow.colorType
}
} catch (e) {}
}
if (colorType) {
template = options.getShadowTemplate(colorType) + template
}
}
options.emitFile(options.resourcePath, template)
if (res.files) {
Object.keys(res.files).forEach(name => {
options.emitFile(name, res.files[name])
})
}
if (state.options.usingGlobalComponents) {
options.updateUsingGlobalComponents(
resourcePath,
state.options.usingGlobalComponents
)
}
if (
res.generic &&
res.generic.length &&
options.updateGenericComponents
) {
options.updateGenericComponents(
resourcePath,
res.generic
)
}
if (
res.componentGenerics &&
Object.keys(res.componentGenerics).length &&
options.updateComponentGenerics
) {
options.updateComponentGenerics(
resourcePath,
res.componentGenerics
)
}
} else {
res.template = template
}
return res
},
parseComponent,
compileToFunctions,
ssrCompile,
ssrCompileToFunctions,
generateCodeFrame
}
const onRE = /^@|^v-on:/
function removeAttr (el, name) {
if (el.attrsMap.hasOwnProperty(name)) {
delete el.attrsMap[name]
el.attrsList.splice(el.attrsList.findIndex(attr => attr.name === name), 1)
return true
}
}
module.exports = {
preTransformNode (el, {
warn
}) {
if (el.tag === 'slot' && !el.attrsMap['name']) {
el.attrsList.push({
name: 'SLOT_DEFAULT',
value: true
})
el.attrsMap['SLOT_DEFAULT'] = true
}
// 处理 attr
el.attrsList.forEach(attr => {
if (
attr.name.indexOf('v-model') === 0 &&
attr.name.indexOf('.lazy') !== -1
) {
const origName = attr.name
const newName = origName.replace('.lazy', '')
attr.name = newName
el.attrsMap[newName] = attr.value
delete el.attrsMap[origName]
} else if (onRE.test(attr.name) && !attr.value.trim()) { // 事件为空
attr.value = '__HOLDER__'
el.attrsMap[attr.name] = attr.value
}
})
// 暂不支持的指令
const dirs = ['v-once', 'v-pre', 'v-cloak']
dirs.forEach(dir => {
if (removeAttr(el, dir)) {
warn(`unsupported directive ${dir}`, false, true)
}
})
//
}
}
const mpBase = require('./mp-base')
const mpWeixin = require('./mp-weixin')
const mpBaidu = require('./mp-baidu')
const mpAlipay = require('./mp-alipay')
const mpToutiao = require('./mp-toutiao')
module.exports = {
'app-plus': Object.assign({
name: 'app-plus'
}, mpBase, mpWeixin),
'mp-weixin': Object.assign({
name: 'mp-weixin'
}, mpBase, mpWeixin),
'mp-qq': Object.assign({
name: 'mp-qq'
}, mpBase, mpWeixin),
'mp-baidu': Object.assign({
name: 'mp-baidu'
}, mpBase, mpBaidu),
'mp-alipay': Object.assign({
name: 'mp-alipay'
}, mpBase, mpAlipay),
'mp-toutiao': Object.assign({
name: 'mp-toutiao'
}, mpBase, mpToutiao)
}
const t = require('@babel/types')
const {
capitalize
} = require('../util')
const EVENTS = {
'click': 'tap',
'touchstart': 'touchStart',
'touchmove': 'touchMove',
'touchend': 'touchEnd',
'touchcancel': 'touchCancel',
'longtap': 'longTap',
'longpress': 'longTap',
'transitionend': 'transitionEnd',
'animationstart': 'animationStart',
'animationiteration': 'animationIteration',
'animationend': 'animationEnd',
'firstappear': 'firstAppear',
// map
'markertap': 'markerTap',
'callouttap': 'calloutTap',
'controltap': 'controlTap',
'regionchange': 'regionChange',
// scroll-view
'scrolltoupper': 'scrollToUpper',
'scrolltolower': 'scrollToLower',
// movable-view
'changeend': 'changeEnd'
}
module.exports = {
prefix: 'a:',
specialEvents: {
'form': {
'reset': 'onReset'
},
'map': {
'markertap': 'onMarkerTap',
'controltap': 'onControlTap',
'callouttap': 'onCalloutTap',
'regionchange': 'onRegionChange'
}
},
getEventType (eventType) {
return EVENTS[eventType] || eventType
},
formatEventType: function (eventName, isCatch) {
return `${isCatch ? 'catch' : 'on'}${capitalize(eventName)}`
},
createScopedSlots (slotName, props, state) {
const node = {
type: 'slot',
attr: {
name: slotName
},
children: []
}
Object.keys(props).forEach(name => {
node.attr[name] = props[name]
})
return node
},
resolveScopedSlots (slotName, {
paramExprNode,
returnExprNodes,
traverseExpr,
normalizeChildren
}, state) {
const node = {
type: 'view',
attr: {
slot: slotName
},
children: normalizeChildren(traverseExpr(returnExprNodes, state))
}
if (t.isIdentifier(paramExprNode)) {
node.scoped = paramExprNode.name
}
return node
}
}
const t = require('@babel/types')
module.exports = {
prefix: 's-',
createScopedSlots (slotName, props, state) {
const node = {
type: 'slot',
attr: {
name: slotName
},
children: []
}
Object.keys(props).forEach(name => {
node.attr['var-' + name] = props[name].replace('{{', '').replace('}}', '')
})
return node
},
resolveScopedSlots (slotName, {
paramExprNode,
returnExprNodes,
traverseExpr,
normalizeChildren
}, state) {
const node = {
type: 'view',
attr: {
slot: slotName
},
children: normalizeChildren(traverseExpr(returnExprNodes, state))
}
if (t.isIdentifier(paramExprNode)) {
node.scoped = paramExprNode.name
}
return node
}
}
const EVENTS = {
click: 'tap'
}
const tags = [
'slot',
'block',
'component',
'template',
'ad',
'audio',
'button',
'camera',
'canvas',
'checkbox',
'checkbox-group',
'cover-image',
'cover-view',
'form',
'functional-page-navigator',
'icon',
'image',
'input',
'label',
'live-player',
'live-pusher',
'map',
'movable-area',
'movable-view',
'navigator',
'official-account',
'open-data',
'picker',
'picker-view',
'picker-view-column',
'progress',
'radio',
'radio-group',
'rich-text',
'scroll-view',
'slider',
'swiper',
'swiper-item',
'switch',
'text',
'textarea',
'video',
'view',
'web-view',
'editor'
]
module.exports = {
ref: 'data-ref',
refInFor: 'data-ref-in-for',
specialEvents: {},
/**
* TODO 暂时先简单判断是不是自定义组件,
* 如果要依赖真实导入的组件识别,需要 template-loader 与 script-loader 结合,
* 目前 template 在前,script 在后,要做的话,就需要把 wxml 的生成机制放到 plugin 中才可以拿到真实的组件列表
*/
isComponent (tagName) {
return !tags.includes(tagName)
},
getEventType (eventType) {
return EVENTS[eventType] || eventType
},
formatEventType (eventName, isCatch, isCapture, isCustom) {
let eventType = 'bind'
if (isCatch) {
eventType = 'catch'
}
if (isCapture) {
return `capture-${eventType}:${eventName}`
}
if (isCustom) {
return `${eventType}:${eventName}`
}
return `${eventType}${eventName}` // 原生组件不支持 bind:input 等写法,统一使用 bindinput
},
createScopedSlots (slotName, props, state) {
state.errors.add('暂不支持 scoped slot [' + slotName + ']')
return {
type: 'slot',
attr: {
name: slotName
},
children: []
}
},
resolveScopedSlots (slotName, componentName, paramExprNode, returnExprNodes, {
traverseExpr,
normalizeChildren
}, state) {
state.errors.add('暂不支持 scoped slot [' + slotName + ']')
return {
type: 'view',
attr: {
slot: slotName
},
children: []
}
}
}
const mpWeixin = require('./mp-weixin')
module.exports = Object.assign({}, mpWeixin, {
prefix: 'tt:'
// ref: 'vue-ref'
})
const path = require('path')
const t = require('@babel/types')
function generateJsCode (properties = '{}') {
return `
wx.createComponent({
generic:true,
props: ${properties},
render: function(){}
})
`
}
module.exports = {
prefix: 'wx:',
createScopedSlots (slotName, props, state) {
const componentName = 'scoped-slots-' + slotName
if (!state.componentGenerics) {
state.componentGenerics = Object.create(null)
}
state.componentGenerics[componentName] = true
return {
type: componentName,
attr: props || {},
children: []
}
},
resolveScopedSlots (slotName, {
genCode,
generate,
ownerName,
parentName,
parentNode,
resourcePath,
paramExprNode,
returnExprNodes,
traverseExpr
}, state) {
if (!state.scopedSlots) {
state.scopedSlots = {}
}
let componentName = `${ownerName}-${parentName}-${slotName}`
if (!state.scopedSlots.hasOwnProperty(componentName)) {
state.scopedSlots[componentName] = 0
}
if (state.scopedSlots[componentName]) {
componentName = componentName + state.scopedSlots[componentName]
}
state.scopedSlots[componentName]++
parentNode.attr['generic:scoped-slots-' + slotName] = componentName
if (!parentNode.attr.generic) {
parentNode.attr.generic = {}
}
parentNode.attr.generic[slotName] = true
// 生成 scopedSlots 文件,包括 json,js,wxml,还需要更新 owner 的 usingComponents
if (!state.files) {
state.files = {}
}
const extname = path.extname(resourcePath)
// TODO 需要存储 resourcePath 相关 json
const templateFile = resourcePath.replace(ownerName + extname, componentName + extname)
const templateContent = generate(traverseExpr(returnExprNodes, state), state)
state.files[templateFile] = templateContent
const jsFile = resourcePath.replace(ownerName + extname, componentName + '.js')
const objectProperties = []
if (t.isObjectPattern(paramExprNode)) {
paramExprNode.properties.forEach(property => {
const key = property.key
const value = property.value
const valueObjectProperties = [
t.objectProperty(t.identifier('type'), t.nullLiteral())
]
if (t.isIdentifier(value)) {
if (value.name !== key.name) {
state.errors.add(`解构插槽 Prop 时,不支持将${key.name}重命名为${value.name},重命名后会影响性能`)
}
} else if (t.isAssignmentPattern(value)) {
valueObjectProperties.push(t.objectProperty(t.identifier('default'), value.right))
}
objectProperties.push(t.objectProperty(key, t.objectExpression(valueObjectProperties)))
})
} else {
state.errors.add(`目前仅支持解构插槽 ${paramExprNode.name},如 v-slot="{ user }"`)
}
const jsContent = generateJsCode(genCode(t.objectExpression(objectProperties), true))
state.files[jsFile] = jsContent
if (!state.generic) {
state.generic = []
}
// 存储,方便后续生成 json
state.generic.push(componentName)
return ''
}
}
const babelGenerate = require('@babel/generator').default
module.exports = function generate (ast, state) {
return babelGenerate(ast, state.options).code
}
const {
IDENTIFIER_ATTR
} = require('../../../constants')
const getMemberExpr = require('../member-expr')
module.exports = function processAttrs (paths, path, state, isComponent, tagName) {
const attrsPath = paths['attrs']
if (attrsPath) {
attrsPath.get('value.properties').forEach(propertyPath => {
const valuePath = propertyPath.get('value')
if (valuePath.isObjectExpression()) {
valuePath.replaceWith(getMemberExpr(null, IDENTIFIER_ATTR, valuePath.node, state))
}
})
}
return []
}
const t = require('@babel/types')
const {
getCode
} = require('../../../util')
function processClassArrayExpressionElements (classArrayExpression) {
let binaryExpression
classArrayExpression.elements.forEach(expr => {
if (!binaryExpression) {
binaryExpression = t.parenthesizedExpression(expr)
} else {
binaryExpression = t.parenthesizedExpression(t.binaryExpression(
'+',
t.binaryExpression(
'+',
binaryExpression,
t.stringLiteral(' ')
),
expr
))
}
})
return binaryExpression
}
function processStaticClass (classArrayExpression, staticClassPath, state) {
if (staticClassPath) {
classArrayExpression.elements.unshift(
t.stringLiteral(staticClassPath.node.value.value)
)
staticClassPath.remove()
}
if (
state.options.platform.name === 'mp-toutiao' ||
state.options.platform.name === 'mp-alipay'
) {
// classArrayExpression => binaryExpression
return processClassArrayExpressionElements(classArrayExpression)
}
return classArrayExpression
}
function processClassObjectExpression (classValuePath) {
const elements = []
const propertyPaths = classValuePath.get('properties')
propertyPaths.forEach(propertyPath => {
const key = propertyPath.node.key
elements.push(
t.conditionalExpression(
t.parenthesizedExpression(propertyPath.node.value),
t.stringLiteral(key.name || key.value),
t.stringLiteral('')
)
)
})
return t.arrayExpression(elements)
}
function processClassArrayExpression (classValuePath) {
const elementPaths = classValuePath.get('elements')
elementPaths.forEach(elementPath => {
if (elementPath.isObjectExpression()) {
elementPath.replaceWith(processClassObjectExpression(elementPath))
}
})
return classValuePath.node
}
module.exports = function processClass (paths, path, state) {
const classPath = paths['class']
const staticClassPath = paths['staticClass']
if (classPath) {
const classValuePath = classPath.get('value')
if (classValuePath.isObjectExpression()) { // object
classValuePath.replaceWith(
processStaticClass(
processClassObjectExpression(classValuePath),
staticClassPath,
state
)
)
} else if (classValuePath.isArrayExpression()) { // array
classValuePath.replaceWith(
processStaticClass(
processClassArrayExpression(classValuePath),
staticClassPath,
state
)
)
} else if (
classValuePath.isStringLiteral() || // :class="'a'"
classValuePath.isIdentifier() || // TODO 需要优化到下一个条件,:class="classObject"
classValuePath.isMemberExpression() || // 需要优化到下一个条件,:class="item.classObject"
classValuePath.isConditionalExpression() ||
classValuePath.isLogicalExpression() ||
classValuePath.isBinaryExpression()
) {
// 理论上 ConditionalExpression,LogicalExpression 可能存在 classObject,应该__get_class,还是先不考虑这种情况吧
// ConditionalExpression :class="index === currentIndex ? activeStyle : itemStyle"
// BinaryExpression :class="'m-content-head-'+message.user"
classValuePath.replaceWith(
processStaticClass(
t.arrayExpression([classValuePath.node]),
staticClassPath,
state
)
)
} else if (
classValuePath.isIdentifier() ||
classValuePath.isMemberExpression()
) { // classObject :class="classObject" :class="vm.classObject"
// TODO 目前先不考虑 classObject,styleObject
// const args = [classPath.node.value]
// if (staticClassPath) {
// args.push(staticClassPath.node.value)
// staticClassPath.remove()
// }
// classValuePath.replaceWith(
// getMemberExpr(
// classPath,
// IDENTIFIER_CLASS,
// t.callExpression(t.identifier(INTERNAL_GET_CLASS), args),
// state
// )
// )
} else {
state.errors.add(`:class 不支持 ${getCode(classValuePath.node)} 语法`)
}
}
return []
}
const t = require('@babel/types')
const {
CLASS_REF,
CLASS_REF_IN_FOR
} = require('../../../constants')
module.exports = function processRef (paths, path, state) {
const refPath = paths['ref']
if (refPath) {
if (state.options.platform.name === 'mp-alipay') {
return [
t.objectProperty( // data-ref="" ,data-ref-in-for=""
t.stringLiteral('ref'),
t.stringLiteral('__r')
),
t.objectProperty( // data-ref="" ,data-ref-in-for=""
t.stringLiteral(state.inFor ? state.options.platform.refInFor : state.options.platform.ref),
refPath.node.value
)
]
}
const refClass = state.inFor ? CLASS_REF_IN_FOR : CLASS_REF
const staticClassPath = paths['staticClass']
if (staticClassPath) { // append
staticClassPath.node.value.value = staticClassPath.node.value.value + ' ' + refClass
} else { // add staticClass
path.node.properties.unshift(
t.objectProperty(t.identifier('staticClass'), t.stringLiteral(refClass))
)
paths['staticClass'] = path.get('properties').find(
propertyPath => propertyPath.node.key.name === 'staticClass'
)
}
return [
t.objectProperty( // data-ref="" ,头条 vue-ref
t.stringLiteral(state.options.platform.ref),
refPath.node.value
)
]
}
return []
}
// 需要转换 h5 标签至 staticClass 的样式名
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
# @dcloudio/vue-cli-plugin-hbuilderx
> HBuilderX plugin for vue-cli 3
\ No newline at end of file
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册