提交 736ed0ee 编写于 作者: fxy060608's avatar fxy060608

merge feat-quickapp

const fs = require('fs')
const del = require('del')
const path = require('path')
const copy = require('copy')
const rollup = require('rollup')
const genConfig = require('./rollup.config.qa')
const filename = 'vue.' + (process.env.NODE_ENV === 'production' ? 'prod' : 'dev') + '.js'
async function build () {
const bridgeBundle = await rollup.rollup(genConfig('bridge'))
const {
output: bridgeOutput
} = await bridgeBundle.generate({
format: 'iife'
})
const bridgeCode = bridgeOutput[0].code
const appBundle = await rollup.rollup(genConfig('app'))
const {
output: appOutput
} = await appBundle.generate({
format: 'iife',
banner: `
dsl.onInitApp(function({
inst,
context,
instRequireModule
}) {
if(!context.quickapp.dock.makeEvaluateBuildScript){
context.quickapp.dock.makeEvaluateBuildScript = args => args
}
const $app_require$ = instRequireModule;
`,
footer: `
});`
})
const appCode = appOutput[0].code
const pageBundle = await rollup.rollup(genConfig('page'))
const {
output: pageOutput
} = await pageBundle.generate({
format: 'iife',
banner: `
dsl.onInitPage(function({
$app_require$,
Vue
}) {
`,
footer: `
});`
})
const pageCode = pageOutput[0].code
const vueCode = fs.readFileSync(path.resolve(__dirname, '../packages/uni-quickapp/assets/' + filename))
fs.writeFileSync(
path.resolve(__dirname, '../packages/uni-quickapp/dist/' + filename),
vueCode + bridgeCode + appCode + pageCode, {
encoding: 'utf8'
}
)
if (process.env.NODE_ENV === 'production') { // 命令会执行dev,prod两次,仅prod时执行copy
const componentsSrc = path.resolve(__dirname, '../src/platforms/quickapp/view/components/**/*')
const componentsDest = path.resolve(__dirname, '../packages/uni-quickapp/components')
del.sync([componentsDest])
copy(componentsSrc, componentsDest, function (err, file) {
if (err) {
throw err
}
})
}
}
build()
const path = require('path')
const alias = require('rollup-plugin-alias')
const replace = require('rollup-plugin-replace')
const nodeResolve = require('rollup-plugin-node-resolve')
const commonjs = require('rollup-plugin-commonjs')
const terser = require('rollup-plugin-terser')
const requireContext = require('../lib/rollup-plugin-require-context')
process.env.UNI_PLATFORM = 'quickapp'
const external = []
const resolve = dir => path.resolve(__dirname, '../', dir)
function replaceModuleImport (str) {
return str.replace(
/require\s*\(\s*(['"])@([\w$_][\w$-.]*?)\1\)/gm,
(e, r, p) => `$app_require$(${r}@app-module/${p}${r})`
).replace(
/import\s+([\w${}]+?)\s+from\s+(['"])@([\w$_][\w$-.]*?)\2/gm,
(e, r, p, t) => `var ${r} = $app_require$(${p}@app-module/${t}${p})`
)
}
const plugins = [{
name: 'replaceModuleImport',
transform (source) {
return {
code: replaceModuleImport(source)
}
}
},
alias({
'uni-core': resolve('src/core'),
'uni-platform': resolve('src/platforms/' + process.env.UNI_PLATFORM),
'uni-platforms': resolve('src/platforms'),
'uni-shared': resolve('src/shared/index.js'),
'uni-helpers': resolve('src/core/helpers'),
'uni-invoke-api': resolve('src/platforms/quickapp/service/invoke-api'),
'uni-service-api': resolve('src/platforms/quickapp/service/api'),
'uni-api-protocol': resolve('src/core/helpers/protocol')
}),
nodeResolve(),
requireContext(),
commonjs(),
replace({
__PLATFORM__: JSON.stringify(process.env.UNI_PLATFORM),
__PLATFORM_TITLE__: '快应用'
})
]
// if (process.env.NODE_ENV === 'production') {
plugins.push(terser.terser())
// }
module.exports = function (type) {
let input = ''
if (type === 'bridge') {
input = 'src/platforms/quickapp/runtime/bridge.js'
} else if (type === 'app') {
input = 'src/platforms/quickapp/runtime/app.js'
} else if (type === 'page') {
input = 'src/platforms/quickapp/runtime/page.js'
}
return {
input,
plugins,
external
}
}
......@@ -23,6 +23,7 @@
"build:mp-toutiao": "cross-env UNI_PLATFORM=mp-toutiao rollup -c build/rollup.config.mp.js",
"build:mp-weixin:mp": "npm run lint && cross-env UNI_PLATFORM=mp-weixin UNI_MP=true rollup -c build/rollup.config.mp.js",
"build:mp-weixin:wxs": "rollup -c build/rollup.config.wxs.js",
"build:quickapp": "cross-env NODE_ENV=development node build/build.qa.js && cross-env NODE_ENV=production node build/build.qa.js",
"build:runtime": "npm run lint && npm run build:mp-weixin && npm run build:mp-qq && npm run build:mp-alipay && npm run build:mp-baidu && npm run build:mp-toutiao && npm run build:app-plus",
"build:stat": "npm run lint && rollup -c build/rollup.config.stat.js",
"build:web-view": "npm run lint && rollup -c build/rollup.config.web-view.js",
......@@ -70,8 +71,10 @@
"rollup-plugin-alias": "^1.4.0",
"rollup-plugin-babel": "^4.3.3",
"rollup-plugin-commonjs": "^10.0.1",
"rollup-plugin-inject": "^3.0.2",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-replace": "^2.1.0",
"rollup-plugin-terser": "^5.2.0",
"rollup-plugin-uglify": "^6.0.3",
"shell-exec": "^1.0.2",
"strip-json-comments": "^2.0.1",
......@@ -139,4 +142,4 @@
"main": "index.js",
"description": "",
"author": ""
}
}
......@@ -334,21 +334,41 @@ let uniAutoImportComponents = []
let uniAutoImportScanComponents = []
function initAutoImportScanComponents () {
const componentsPath = path.resolve(process.env.UNI_INPUT_DIR, 'components')
let uniQuickAppAutoImportScanComponents = false
function getAutoComponentsByDir (componentsPath, absolute = false) {
const components = {}
try {
fs.readdirSync(componentsPath).forEach(name => {
if (fs.existsSync(path.resolve(componentsPath, name, name + '.vue'))) {
components[`^${name}$`] = `@/components/${name}/${name}.vue`
} else if (fs.existsSync(path.resolve(componentsPath, name, name + '.nvue'))) {
components[`^${name}$`] = `@/components/${name}/${name}.nvue`
const folder = path.resolve(componentsPath, name)
const importDir = absolute ? normalizePath(folder) : `@/components/${name}`
if (fs.existsSync(path.resolve(folder, name + '.vue'))) {
components[`^${name}$`] = `${importDir}/${name}.vue`
} else if (fs.existsSync(path.resolve(folder, name + '.nvue'))) {
components[`^${name}$`] = `${importDir}/${name}.nvue`
}
})
} catch (e) {}
return components
}
uniAutoImportScanComponents = parseUsingAutoImportComponents(components)
function initAutoImportScanComponents () {
const componentsPath = path.resolve(process.env.UNI_INPUT_DIR, 'components')
const components = getAutoComponentsByDir(componentsPath)
if (process.env.UNI_PLATFORM === 'quickapp') {
if (!uniQuickAppAutoImportScanComponents) {
uniQuickAppAutoImportScanComponents = getAutoComponentsByDir(
path.resolve(require.resolve('@dcloudio/uni-quickapp'), '../../components'),
true
)
}
// 平台内置组件优先级高
Object.assign(components, uniQuickAppAutoImportScanComponents)
}
uniAutoImportScanComponents = parseUsingAutoImportComponents(components)
refreshAutoComponentMap()
}
......
......@@ -337,6 +337,23 @@ const PLATFORMS = {
...getCopyOptions(['ttcomponents'])
]
}
},
'quickapp': {
vue: '@dcloudio/vue-cli-plugin-uni/packages/h5-vue',
subPackages: false,
cssVars: {
'--status-bar-height': '25px',
'--window-top': '0px',
'--window-bottom': '0px'
},
copyWebpackOptions ({
assetsDir
}) {
return [
...getStaticCopyOptions(assetsDir),
...getCopyOptions(['qacomponents'])
]
}
}
}
// 解决 vue-cli-service lint 时 UNI_PLATFORM 不存在
......@@ -564,7 +581,11 @@ module.exports = {
return platform.vue
},
getPlatformCompiler () {
if (process.env.UNI_USING_COMPONENTS || process.env.UNI_PLATFORM === 'h5') {
if (
process.env.UNI_USING_COMPONENTS ||
process.env.UNI_PLATFORM === 'h5' ||
process.env.UNI_PLATFORM === 'quickapp'
) {
return require(uniCompiler)
}
return require(platform.compiler)
......@@ -579,7 +600,7 @@ module.exports = {
mergeLonghand: false,
mergeRules: false,
cssDeclarationSorter: false,
uniqueSelectors: false, // 标签排序影响头条小程序
uniqueSelectors: false, // 标签排序影响头条小程序
minifySelectors: false, // 标签排序影响头条小程序
discardComments: false,
discardDuplicates: false // 条件编译会导致重复
......
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
1.解析pages.json,manifest.json 输出 manifest.json ,webpack entries
2.webpack 增加各种loader
1.copy dsl.js
\ No newline at end of file
此差异已折叠。
此差异已折叠。
const path = require('path')
const moduleAlias = require('module-alias')
moduleAlias.addAlias('../service', (fromPath, request, alias) => {
// @hap-toolkit/packager/lib/router/routes/index.js
if (fromPath.indexOf('/@hap-toolkit') !== -1 && fromPath.indexOf('packager') !== -1) {
return path.resolve(__dirname, 'service.js')
}
return path.join(fromPath, '..', request)
})
require('@hap-toolkit/server').launchServer({})
"use strict";
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.getProjectName = getProjectName, exports.getServerAddress = getServerAddress, exports.getClientFromRequest =
getClientFromRequest, exports.getDistFilePath = getDistFilePath, exports.serverConf = serverConf, exports.LINK_MODE =
void 0;
var _path = _interopRequireDefault(require("path")),
_fs = _interopRequireDefault(require("fs")),
_sharedUtils = require("@hap-toolkit/shared-utils");
function _interopRequireDefault(e) {
return e && e.__esModule ? e : {
default: e
}
}
const LINK_MODE = {
NULL: 0,
WIFI: 1,
ADB: 2
};
function getProjectName(e, t) {
try {
const stripJsonComments = require('strip-json-comments');
const r = _path.default.join(e, t, "manifest.json");
const s = JSON.parse(stripJsonComments(_fs.default.readFileSync(r).toString()))
return s && s.quickapp && s.quickapp.package || "Bundle"
} catch (e) {
_sharedUtils.colorconsole.error(`### App Server ### 获取项目名称出错:${e.message}`)
}
}
function getServerAddress(e) {
return `http://${(0,_sharedUtils.getIPv4IPAddress)()}${80===e?"":":"+e}`
}
function getClientFromRequest(e) {
const t = (0, _sharedUtils.getClientIPAddress)(e),
r = (0, _sharedUtils.getIPv4IPAddress)(),
s = e.header["device-serial-number"];
let i = LINK_MODE.NULL;
return "127.0.0.1" === t && s ? i = LINK_MODE.ADB : "127.0.0.1" !== t && t !== r && (i = LINK_MODE.WIFI), {
clientIp: t,
sn: s,
linkMode: i
}
}
function getDistFilePath(e, t, r) {
let s;
if (!process.env.UNI_OUTPUT_DIR) {
const mode = process.env.NODE_ENV === 'production' ? 'build' : 'dev'
process.env.UNI_OUTPUT_DIR = _path.default.join(process.cwd(), 'dist/' + mode + '/quickapp')
}
return s = _path.default.join(process.env.UNI_OUTPUT_DIR, `${t}.debug.${r}`), _fs.default.existsSync(s) ? s : (s =
_path.default.join(e,
`${t}.release.${r}`), _fs.default.existsSync(s) ? s : void 0)
}
function serverConf(e) {
return e.conf
}
exports.LINK_MODE = LINK_MODE;
<template>
<div v-on="$listeners">
<text>
<slot />
</text>
</div>
</template>
<script>
export default {
name: 'Button'
}
</script>
<style>
</style>
此差异已折叠。
此差异已折叠。
module.exports = config => {
config.module
.rule('vue')
.test([/\.vue$/, /\.nvue$/])
.use('vue-loader')
.loader(require.resolve('@dcloudio/vue-cli-plugin-uni/packages/vue-loader'))
.tap(options => Object.assign(options, {
compiler: require('@dcloudio/uni-template-compiler'),
compilerOptions: {
quickapp: true,
preserveWhitespace: false
},
hotReload: false,
cacheDirectory: false,
cacheIdentifier: false
}))
config.module
.rule('vue')
.uses
.delete('cache-loader')
config.plugin('extract-css')
.init((Plugin, args) => new Plugin({
filename: '[name].css.json'
}))
config.plugins.delete('hmr')
config.plugins.delete('html')
config.plugins.delete('copy')
config.plugins.delete('preload')
config.plugins.delete('prefetch')
}
module.exports = {
preTransformNode(el) {
if (el.tag === 'view') { // view 是最常用组件,直接映射为div标签,保证性能
el.tag = 'div'
}
}
}
const path = require('path')
const webpack = require('webpack')
const CopyPlugin = require('copy-webpack-plugin')
const HandlerPlugin = require('@hap-toolkit/packager/lib/plugin/handler-plugin')
const ZipPlugin = require('@hap-toolkit/packager/lib/plugin/zip-plugin')
const NotifyPlugin = require('@hap-toolkit/packager/lib/plugin/notify-plugin')
const Css2jsonPlugin = require('@hap-toolkit/dsl-vue/lib/plugin/css2json-plugin')
const InstVuePlugin = require('@hap-toolkit/dsl-vue/lib/plugin/instvue-plugin')
const InstMainPlugin = require('./plugin/main-plugin')
const parseManifest = require('./manifest/index')
const env = {
// 平台:native
NODE_PLATFORM: 'native',
// 阶段: dev|test|release
NODE_PHASE: process.env.NODE_PHASE
}
const dslFilename = ('vue.' + (process.env.NODE_ENV === 'production' ? 'prod' : 'dev') + '.js')
parseManifest(process.UNI_PAGES, process.UNI_MANIFEST)
const manifest = global.framework.manifest
if (!manifest.package) {
console.error(`maniest.json quickapp 节点缺少 package 配置`)
process.exit(0)
}
function genPriorities(entryPagePath) {
const o = [/^i18n\/.+\.json$/i, 'manifest.json', 'app.js', /^common\//i];
if (entryPagePath) {
o.splice(3, 0, new RegExp(`^${entryPagePath}/$`), new RegExp(`^${entryPagePath}/.+`))
} else console.error('未配置入口页面');
return o
}
module.exports = {
devtool: false,
entry() {
return process.UNI_ENTRY
},
externals: {
vue: 'Vue'
},
module: {
rules: [{
//暂不考虑ts
test: path.resolve(process.env.UNI_INPUT_DIR, 'main.js'),
use: [{
loader: path.resolve(__dirname, 'loader/main-loader')
}]
}]
},
plugins: [
new webpack.DefinePlugin({
// 平台:na
ENV_PLATFORM: JSON.stringify(env.NODE_PLATFORM),
// 阶段: dev|test|release
ENV_PHASE: JSON.stringify(env.NODE_PHASE),
ENV_PHASE_DV: env.NODE_PHASE === 'dev',
ENV_PHASE_QA: env.NODE_PHASE === 'test',
ENV_PHASE_OL: env.NODE_PHASE === 'prod'
}),
new CopyPlugin([{
from: path.resolve(__dirname, '../dist/' + dslFilename),
to: 'dsl.js'
}]),
new HandlerPlugin({}),
new Css2jsonPlugin(),
new InstVuePlugin(),
new InstMainPlugin(),
new ZipPlugin({
name: manifest.package,
icon: manifest.icon,
versionCode: manifest.versionCode,
output: path.resolve(process.env.UNI_OUTPUT_DIR, '..'),
pathBuild: process.env.UNI_OUTPUT_DIR,
pathSignFolder: './sign',
sign: process.env.NODE_ENV === 'production' ? 'release' : 'debug',
priorities: genPriorities(manifest.router.entry),
subpackages: undefined,
comment: '',
cwd: process.env.UNI_INPUT_DIR,
disableStreamPack: undefined,
disableSubpackages: undefined
}),
new NotifyPlugin()
]
}
module.exports = function(source, map) {
return `
import 'uni-pages';
${source}
export default App;
`
}
const ATTRS = {
'name': 'name',
'versionName': 'versionName',
'versionCode': 'versionCode'
}
function merge(to, from) {
Object.keys(ATTRS).forEach(name => {
if (!to[name]) {
to[name] = from[name]
}
})
}
module.exports = function parseBase(manifest, manifestJson) {
merge(manifest, manifestJson)
manifest.versionCode = parseInt(manifest.versionCode) || 1
if (!manifest.config) {
manifest.config = {}
}
if (!manifest.config.dsl) {
manifest.config.dsl = {}
}
manifest.config.dsl.name = 'vue'
return manifest
}
const PLATFORMS = [
'h5',
'app-plus',
'mp-weixin',
'mp-qq',
'mp-baidu',
'mp-alipay',
'mp-toutiao',
'quickapp'
]
const DISPLAY = {
'navigationBarBackgroundColor': 'titleBarBackgroundColor',
'navigationBarTextStyle': (style, val) => {
if (val === 'black') {
style.titleBarTextColor = '#000000'
style.statusBarTextStyle = 'dark'
} else {
style.titleBarTextColor = '#ffffff'
style.statusBarTextStyle = 'light'
}
},
'navigationBarTitleText': 'titleBarText',
'navigationStyle': (style, val) => {
if (val === 'custom') {
style.titleBar = false
}
}
}
function parseStyle(style = {}) {
const ret = {}
Object.keys(style).forEach(name => {
if (!PLATFORMS.includes(name)) {
const transform = DISPLAY[name]
if (transform) {
if (typeof transform === 'string') {
ret[transform] = style[name]
} else if (typeof transform === 'function') {
transform(ret, style[name])
}
} else {
ret[name] = style[name]
}
}
})
if (style.quickapp) {
Object.assign(ret, style.quickapp)
}
return ret
}
module.exports = function parseDisplay(manifest, pages, globalStyle = {}) {
const display = {
pages: {}
}
// globalStyle
Object.assign(display, parseStyle(globalStyle))
pages.forEach(page => {
const key = page.path.substr(0, page.path.lastIndexOf('/'))
display.pages[key] = parseStyle(page.style)
})
manifest.display = display
}
const path = require('path')
module.exports = function parseEntry(pages) {
const entry = {
'app': path.resolve(process.env.UNI_INPUT_DIR, 'main.js')
}
pages.forEach(page => {
entry[page.path] = path.resolve(process.env.UNI_INPUT_DIR, page.path + '.vue?uxType=page')
})
return entry
}
const parseBase = require('./base-parser')
const parsePages = require('./pages-parser')
const parseDisplay = require('./display-parser')
const parseEntry = require('./entry-parser')
module.exports = function(pagesJson, manifestJson, loader) {
const manifest = manifestJson.quickapp || {}
parseBase(manifest, manifestJson)
parsePages(manifest, pagesJson.pages)
parseDisplay(manifest, pagesJson.pages, pagesJson.globalStyle)
process.UNI_ENTRY = parseEntry(pagesJson.pages)
global.framework.manifest = manifest
loader && loader.emitFile('manifest.json', JSON.stringify(manifest))
return ''
}
module.exports = function parsePages(manifest, pages) {
const entryPagePath = pages[0].path
const router = {
entry: entryPagePath.substr(0, entryPagePath.lastIndexOf('/')),
pages: {}
}
pages.forEach(page => {
const lastIndex = page.path.lastIndexOf('/')
const key = page.path.substr(0, lastIndex)
router.pages[key] = {
component: page.path.substr(lastIndex + 1)
}
})
manifest.router = router
}
const WebpackSources = require('webpack-sources')
class InstMainPlugin {
apply(compiler) {
compiler.hooks.compilation.tap('InstMainPlugin', (compilation) => {
compilation.hooks.optimizeChunkAssets.tapAsync('InstMainPlugin', (chunks, callback) => {
if (chunks.find(chunk => chunk.files.includes('app.js'))) {
const appAsset = compilation.assets['app.js']
compilation.assets['app.js'] =
new WebpackSources.ConcatSource(
`(function(){\n var handler = function() {\n return `, appAsset,
`\n };\n if (typeof window === "undefined") {\n let options = handler();\n options.default['manifest'] = ${JSON.stringify(global.framework.manifest)}\n $app_define$(options.default)\n $app_bootstrap$()\n }\n })();`
)
}
callback()
})
})
}
}
module.exports = InstMainPlugin
global.framework = {}
const chainWebpack = require('./chain-webpack')
const configureWebpack = require('./configure-webpack')
module.exports = {
chainWebpack,
configureWebpack
}
{
"name": "@dcloudio/uni-quickapp",
"version": "2.0.0-alpha-24720191216006",
"description": "uni-app quickapp",
"main": "dist/vue.prod.js",
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-quickapp"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "fxy060608",
"license": "Apache-2.0",
"gitHead": "110501ffb0313e417858dec92acf07522d4ded00",
"dependencies": {
"@hap-toolkit/dsl-vue": "0.6.13",
"@hap-toolkit/packager": "0.6.13",
"@hap-toolkit/server": "0.6.13",
"module-alias": "^2.1.0"
}
}
......@@ -86,7 +86,10 @@ function compileTemplate (source, options, compile) {
const compilerModule = {
preTransformNode (el, options) {
if (isComponent(el.tag) && el.tag !== 'App') { // App.vue
if (process.env.UNI_PLATFORM === 'quickapp') {
// 排查所有标签
(options.isUnaryTag.autoComponents || (options.isUnaryTag.autoComponents = new Set())).add(el.tag)
} else if (isComponent(el.tag) && el.tag !== 'App') { // App.vue
// 挂在 isUnaryTag 上边,可以保证外部访问到
(options.isUnaryTag.autoComponents || (options.isUnaryTag.autoComponents = new Set())).add(el.tag)
}
......@@ -95,4 +98,4 @@ const compilerModule = {
module.exports = {
compileTemplate,
module: compilerModule
}
}
......@@ -72,9 +72,12 @@ module.exports = {
console.error(source)
throw e
}
} else if (options.quickapp) {
// 后续改版,应统一由具体包实现
(options.modules || (options.modules = [])).push(require('@dcloudio/uni-quickapp/lib/compiler-module'))
}
if (!options.mp) { // h5
if (!options.mp) { // h5,quickapp
return compileTemplate(source, options, compile)
}
......
......@@ -50,7 +50,8 @@ module.exports = (api, options, rootOptions) => {
'@dcloudio/vue-cli-plugin-uni-optimize': version,
'@dcloudio/webpack-uni-mp-loader': version,
'@dcloudio/webpack-uni-pages-loader': version,
'babel-plugin-import': '^1.11.0'
'babel-plugin-import': '^1.11.0',
'cross-env': '^7.0.2'
},
browserslist: [
'Android >= 4',
......
......@@ -19,6 +19,28 @@ module.exports = (api, options) => {
initBuildCommand(api, options)
if (process.env.UNI_PLATFORM === 'quickapp') {
process.env.UNI_OUTPUT_DIR = path.resolve(process.env.UNI_OUTPUT_DIR, 'build')
Object.assign(options, {
assetsDir,
parallel: false,
outputDir: process.env.UNI_OUTPUT_DIR
})
require('./lib/options')(options)
const platformOptions = {
webpackConfig: {},
chainWebpack () {}
}
const manifestPlatformOptions = {}
api.configureWebpack(require('./lib/configure-webpack')(platformOptions, manifestPlatformOptions, options, api))
api.chainWebpack(require('./lib/chain-webpack')(platformOptions, options, api))
const vueConfig = require('@dcloudio/uni-quickapp/lib/vue.config.js')
api.configureWebpack(vueConfig.configureWebpack)
api.chainWebpack(vueConfig.chainWebpack)
return
}
const platformOptions = require('./lib/' + process.env.UNI_PLATFORM)
let vueConfig = platformOptions.vueConfig
......
......@@ -18,27 +18,27 @@ if (process.env.UNI_CLOUD_SPACES) {
if (spaces.length === 1) {
const space = spaces[0]
console.log(`本项目的uniCloud使用的默认服务空间spaceId为:${space.id}`)
}
process.env.UNI_CLOUD_PROVIDER = JSON.stringify(spaces.map(space => {
if (space.clientSecret) {
return {
provider: 'aliyun',
spaceName: space.name,
spaceId: space.id,
clientSecret: space.clientSecret,
endpoint: space.apiEndpoint
}
} else {
return {
provider: 'tencent',
spaceName: space.name,
spaceId: space.id
}
}
}
process.env.UNI_CLOUD_PROVIDER = JSON.stringify(spaces.map(space => {
if (space.clientSecret) {
return {
provider: 'aliyun',
spaceName: space.name,
spaceId: space.id,
clientSecret: space.clientSecret,
endpoint: space.apiEndpoint
}
} else {
return {
provider: 'tencent',
spaceName: space.name,
spaceId: space.id
}
}
}))
}
} catch (e) {}
}
}
if (
process.UNI_CLOUD &&
......@@ -88,7 +88,7 @@ if (process.env.NODE_ENV === 'production') { // 发行模式,不启用 cache
delete process.env.UNI_USING_CACHE
}
const {
const {
normalizePath,
isSupportSubPackages,
runByHBuilderX,
......@@ -120,6 +120,9 @@ if (Array.isArray(pagesJsonObj.subPackages)) {
const manifestJsonObj = getManifestJson()
const platformOptions = manifestJsonObj[process.env.UNI_PLATFORM] || {}
process.UNI_PAGES = pagesJsonObj
process.UNI_MANIFEST = manifestJsonObj
if (manifestJsonObj.debug) {
process.env.VUE_APP_DEBUG = true
}
......@@ -212,7 +215,7 @@ if (process.env.UNI_PLATFORM === 'app-plus') {
normalizePath(path.resolve(process.env.UNI_INPUT_DIR, filepath))
)
}
}
}
} else { // 其他平台,待确认配置方案
if (
manifestJsonObj['app-plus'] &&
......
......@@ -235,19 +235,20 @@ if (process.env.UNI_USING_V3) {
// Transform each property declaration here
decl.value = tranformValue(decl, opts)
})
rule.selectors = rule.selectors.map(complexSelector => {
return transformSelector(complexSelector, simpleSelectors => {
return simpleSelectors.walkTags(tag => {
const k = tag.value
const v = CSS_TAGS[k]
if (v) {
tag.value = v === 'r'
? `._${k}` : v
}
})
})
})
if (process.env.UNI_PLATFORM !== 'quickapp') {
rule.selectors = rule.selectors.map(complexSelector => {
return transformSelector(complexSelector, simpleSelectors => {
return simpleSelectors.walkTags(tag => {
const k = tag.value
const v = CSS_TAGS[k]
if (v) {
tag.value = v === 'r'
? `._${k}` : v
}
})
})
})
}
})
}
}
......
......@@ -69,6 +69,9 @@ module.exports = function (content) {
if (process.env.UNI_PLATFORM === 'h5') {
return require('./platforms/h5')(pagesJson, manifestJson)
}
if (process.env.UNI_PLATFORM === 'quickapp') {
return require('./platforms/quickapp')(pagesJson, manifestJson, this)
}
if (!process.env.UNI_USING_V3) {
parsePages(pagesJson, function (page) {
......
......@@ -41,7 +41,11 @@ module.exports = function (content) {
}
}
if (process.env.UNI_USING_COMPONENTS || process.env.UNI_PLATFORM === 'h5') {
if (
process.env.UNI_USING_COMPONENTS ||
process.env.UNI_PLATFORM === 'h5' ||
process.env.UNI_PLATFORM === 'quickapp'
) {
return require('./index-new').call(this, content)
}
......
module.exports = function (pagesJson, manifestJson, loader) {
return require('@dcloudio/uni-quickapp/lib/manifest')(pagesJson, manifestJson, loader)
}
export default class Emitter {
constructor () {
this._events = Object.create(null)
}
on (event, fn) {
const vm = this
if (Array.isArray(event)) {
for (let i = 0, l = event.length; i < l; i++) {
vm.on(event[i], fn)
}
} else {
(vm._events[event] || (vm._events[event] = [])).push(fn)
}
return vm
}
emit (event, ...args) {
const vm = this
const callbacks = vm._events[event]
if (callbacks) {
const cbs = callbacks.slice(0)
for (let i = 0, l = cbs.length; i < l; i++) {
cbs[i].apply(vm, args)
}
}
return vm
}
}
export {
default
}
from '../../h5/helpers/get-real-path'
import globalRef from '../service/index'
const injectRef = Object.getPrototypeOf(global) || global
function parseRoutes ({
pages
}) {
const routes = []
Object.keys(pages).forEach((folder) => {
const options = pages[folder]
routes.push({
path: '/' + folder + '/' + options.component,
meta: {}
})
})
return routes
}
/* eslint-disable no-undef */
dsl.onDefineApp(def => {
// 处理生命周期
const hasOnLaunch = typeof def.onLaunch === 'function'
const hasOnShow = typeof def.onShow === 'function'
if (hasOnLaunch || hasOnShow) {
(inst._events['applc:onCreate'] || (inst._events['applc:onCreate'] = [])).push(() => {
hasOnLaunch && def.onLaunch()
hasOnShow && def.onShow()
})
}
// __uniRoutes
injectRef.__uniRoutes = parseRoutes(def.manifest.router)
})
Object.assign(injectRef, globalRef)
import Emitter from '../helpers/Emitter'
const injectRef = Object.getPrototypeOf(global) || global
injectRef.UniServiceJSBridge = new Emitter()
injectRef.UniViewJSBridge = new Emitter()
/* eslint-disable no-undef */
if (typeof __VuePlugin !== 'undefined') {
Vue.use(__VuePlugin)
}
import * as baseApi from './base-api'
import * as platformApi from './platform-api'
export default {
...baseApi,
...platformApi
}
import router from '@system.router'
export function navigateBack ({
delta
}) {
// TODO delta
router.back()
return {
errMsg: 'navigateBack:ok'
}
}
import {
parseQuery
} from 'uni-shared'
import {
parseUri
} from './util'
import router from '@system.router'
export function navigateTo ({
url
}) {
const urls = url.split('?')
const path = urls[0]
const query = parseQuery(urls[1] || '')
router.push({
uri: parseUri(path),
params: query
})
return {
errMsg: 'navigateTo:ok'
}
}
import {
parseQuery
} from 'uni-shared'
import {
parseUri
} from './util'
import router from '@system.router'
export function redirectTo ({
url
}) {
const urls = url.split('?')
const path = urls[0]
const query = parseQuery(urls[1] || '')
router.replace({
uri: parseUri(path),
params: query
})
return {
errMsg: 'redirectTo:ok'
}
}
export function parseUri (path) {
return path.substr(0, path.lastIndexOf('/'))
}
// base
export * from 'uni-core/service/api/base/base64'
export * from 'uni-core/service/api/base/can-i-use'
export * from 'uni-core/service/api/base/interceptor'
export * from 'uni-core/service/api/base/upx2px'
export * from 'uni-core/service/api/context/audio'
export * from 'uni-core/service/api/context/background-audio'
// TODO
export function invoke (...args) {
return global.UniServiceJSBridge.invokeCallbackHandler(...args)
}
const defaultApp = {
globalData: {}
}
function wrapper (def) {
if (def.__$processed) {
return def
}
const methods = def.methods
if (methods) {
Object.keys(methods).forEach(name => {
def[name] = methods[name]
})
delete def.methods
}
// merge defaultApp
Object.keys(defaultApp).forEach(name => {
if (name !== 'globalData') {
def[name] = defaultApp[name]
}
})
if (!def.globalData) {
def.globalData = {}
}
Object.assign(def.globalData, defaultApp.globalData)
def.__$processed = true
return def
}
export function getApp ({
allowDefault = false
} = {}) {
/* eslint-disable no-undef */
if (inst.$def) {
return wrapper(inst.$def)
}
if (allowDefault) { // 返回默认实现
return defaultApp
}
}
// TODO 需要自己维护路由堆栈?
export function getCurrentPages () {
return []
}
// 目前仅支持 store, use, mixin, component, prototype
let store
const mixins = []
const plugins = []
const components = []
// fake
function Vue (options) {
if (options && options.store) {
store = options.store
}
}
Vue.prototype.$mount = function () {}
Vue.config = {}
Vue.use = function (plugin) {
plugins.push(plugin)
}
Vue.mixin = function (mixin) {
mixins.push(mixin)
}
Vue.component = function (id, definition) {
components.push({
id,
definition
})
}
const injectRef = Object.getPrototypeOf(global) || global
injectRef.__VuePlugin = {
install (PageVue, options) {
mixins.forEach(mixin => {
PageVue.mixin(mixin)
})
plugins.forEach(plugin => {
PageVue.use(plugin)
})
components.forEach(({
id,
definition
}) => {
PageVue.component(id, definition)
})
Object.keys(Vue.prototype).forEach(name => {
if (name !== '$mount') {
PageVue.prototype[name] = Vue.prototype[name]
}
})
store && (PageVue.prototype.$store = store)
}
}
export default Vue
import {
uni
} from 'uni-core/service/uni'
import {
invokeCallbackHandler
} from 'uni-helpers/api'
import Vue from './framework/vue'
import {
getApp
} from './framework/app'
import {
getCurrentPages
} from './framework/page'
global.UniServiceJSBridge.invokeCallbackHandler = invokeCallbackHandler
// TODO 补充__uniRoutes?路由校验那里用到了
export default {
uni,
Vue,
getApp,
getCurrentPages
}
import * as api from './platform-api'
export default api
export * from './api/route/navigate-back'
export * from './api/route/navigate-to'
export * from './api/route/redirect-to'
export function publishHandler (event, args, pageId) {
// TODO
}
<template>
<div v-on="$listeners">
<text>
<slot />
</text>
</div>
</template>
<script>
export default {
name: 'Button'
}
</script>
<style>
</style>
......@@ -5640,6 +5640,12 @@ magic-string@^0.25.2:
dependencies:
sourcemap-codec "^1.4.4"
magic-string@^0.25.3:
version "0.25.7"
resolved "https://registry.npmjs.org/magic-string/-/magic-string-0.25.7.tgz#3f497d6fd34c669c6798dcb821f2ef31f5445051"
dependencies:
sourcemap-codec "^1.4.4"
make-dir@^2.0.0, make-dir@^2.1.0:
version "2.1.0"
resolved "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz#5f0310e18b8be898cc07009295a30ae41e91e6f5"
......@@ -7515,6 +7521,14 @@ rollup-plugin-commonjs@^10.0.1:
resolve "^1.11.0"
rollup-pluginutils "^2.8.1"
rollup-plugin-inject@^3.0.2:
version "3.0.2"
resolved "https://registry.npmjs.org/rollup-plugin-inject/-/rollup-plugin-inject-3.0.2.tgz#e4233855bfba6c0c12a312fd6649dff9a13ee9f4"
dependencies:
estree-walker "^0.6.1"
magic-string "^0.25.3"
rollup-pluginutils "^2.8.1"
rollup-plugin-node-resolve@^5.2.0:
version "5.2.0"
resolved "https://registry.npmjs.org/rollup-plugin-node-resolve/-/rollup-plugin-node-resolve-5.2.0.tgz#730f93d10ed202473b1fb54a5997a7db8c6d8523"
......@@ -7532,6 +7546,16 @@ rollup-plugin-replace@^2.1.0:
magic-string "^0.25.2"
rollup-pluginutils "^2.6.0"
rollup-plugin-terser@^5.2.0:
version "5.2.0"
resolved "https://registry.npmjs.org/rollup-plugin-terser/-/rollup-plugin-terser-5.2.0.tgz#ba758adf769347b7f1eaf9ef35978d2e207dccc7"
dependencies:
"@babel/code-frame" "^7.5.5"
jest-worker "^24.9.0"
rollup-pluginutils "^2.8.2"
serialize-javascript "^2.1.2"
terser "^4.6.2"
rollup-plugin-uglify@^6.0.3:
version "6.0.4"
resolved "https://registry.npmjs.org/rollup-plugin-uglify/-/rollup-plugin-uglify-6.0.4.tgz#65a0959d91586627f1e46a7db966fd504ec6c4e6"
......@@ -7541,7 +7565,7 @@ rollup-plugin-uglify@^6.0.3:
serialize-javascript "^2.1.2"
uglify-js "^3.4.9"
rollup-pluginutils@^2.6.0, rollup-pluginutils@^2.8.1:
rollup-pluginutils@^2.6.0, rollup-pluginutils@^2.8.1, rollup-pluginutils@^2.8.2:
version "2.8.2"
resolved "https://registry.npmjs.org/rollup-pluginutils/-/rollup-pluginutils-2.8.2.tgz#72f2af0748b592364dbd3389e600e5a9444a351e"
dependencies:
......@@ -8289,6 +8313,14 @@ terser@^4.1.2, terser@^4.4.3:
source-map "~0.6.1"
source-map-support "~0.5.12"
terser@^4.6.2:
version "4.6.6"
resolved "https://registry.npmjs.org/terser/-/terser-4.6.6.tgz#da2382e6cafbdf86205e82fb9a115bd664d54863"
dependencies:
commander "^2.20.0"
source-map "~0.6.1"
source-map-support "~0.5.12"
test-exclude@^5.2.3:
version "5.2.3"
resolved "https://registry.npmjs.org/test-exclude/-/test-exclude-5.2.3.tgz#c3d3e1e311eb7ee405e092dac10aefd09091eac0"
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册