提交 3cb45f8b 编写于 作者: fxy060608's avatar fxy060608

chore(app): init

上级 7dfd02b1
......@@ -35,7 +35,7 @@ module.exports = {
// Packages targeting DOM
{
files: [
'packages/{uni-api,uni-app,uni-components,uni-core,uni-h5,uni-h5-vue,uni-i18n,uni-shared,uni-vue}/**',
'packages/{uni-api,uni-app,uni-components,uni-core,uni-h5,uni-h5-vue,uni-i18n,uni-shared,uni-vue,uni-app-plus}/**',
],
rules: {
'no-restricted-globals': ['error', ...NodeGlobals],
......
{
"input": {
"src/service/index.ts": "dist/uni-app-service.es.js"
},
"output": {
"name": "serviceContext",
"format": "iife",
"banner": "export function createServiceContext(Vue, weex, plus, UniServiceJSBridge,instanceContext){\nconst setTimeout = instanceContext.setTimeout;\nconst clearTimeout = instanceContext.clearTimeout;\nconst setInterval = instanceContext.setInterval;\nconst clearInterval = instanceContext.clearInterval;\nconst __uniConfig = instanceContext.__uniConfig;\nconst __uniRoutes = instanceContext.__uniRoutes;\n",
"footer": "const uni = serviceContext.uni;\nconst getApp = serviceContext.getApp;\nconst getCurrentPages = serviceContext.getCurrentPages;\nconst __definePage = serviceContext.__definePage;\nconst __registerPage = serviceContext.__registerPage;\nreturn serviceContext;\n}"
},
"external": false
}
uni-button {
position: relative;
display: block;
margin-left: auto;
margin-right: auto;
padding-left: 14px;
padding-right: 14px;
box-sizing: border-box;
font-size: 18px;
text-align: center;
text-decoration: none;
line-height: 2.55555556;
border-radius: 5px;
-webkit-tap-highlight-color: transparent;
overflow: hidden;
color: #000000;
background-color: #f8f8f8;
cursor: pointer;
}
uni-button[hidden] {
display: none !important;
}
uni-button:after {
content: ' ';
width: 200%;
height: 200%;
position: absolute;
top: 0;
left: 0;
border: 1px solid rgba(0, 0, 0, 0.2);
transform: scale(0.5);
transform-origin: 0 0;
box-sizing: border-box;
border-radius: 10px;
}
uni-button[native] {
padding-left: 0;
padding-right: 0;
}
uni-button[native] .uni-button-cover-view-wrapper {
border: inherit;
border-color: inherit;
border-radius: inherit;
background-color: inherit;
}
uni-button[native] .uni-button-cover-view-inner {
padding-left: 14px;
padding-right: 14px;
}
uni-button uni-cover-view {
line-height: inherit;
white-space: inherit;
}
uni-button[type='default'] {
color: #000000;
background-color: #f8f8f8;
}
uni-button[type='primary'] {
color: #ffffff;
background-color: #007aff;
}
uni-button[type='warn'] {
color: #ffffff;
background-color: #e64340;
}
uni-button[disabled] {
color: rgba(255, 255, 255, 0.6);
cursor: not-allowed;
}
uni-button[disabled][type='default'],
uni-button[disabled]:not([type]) {
color: rgba(0, 0, 0, 0.3);
background-color: #f7f7f7;
}
uni-button[disabled][type='primary'] {
background-color: rgba(0, 122, 255, 0.6);
}
uni-button[disabled][type='warn'] {
background-color: #ec8b89;
}
uni-button[type='primary'][plain] {
color: #007aff;
border: 1px solid #007aff;
background-color: transparent;
}
uni-button[type='primary'][plain][disabled] {
color: rgba(0, 0, 0, 0.2);
border-color: rgba(0, 0, 0, 0.2);
}
uni-button[type='primary'][plain]:after {
border-width: 0;
}
uni-button[type='default'][plain] {
color: #353535;
border: 1px solid #353535;
background-color: transparent;
}
uni-button[type='default'][plain][disabled] {
color: rgba(0, 0, 0, 0.2);
border-color: rgba(0, 0, 0, 0.2);
}
uni-button[type='default'][plain]:after {
border-width: 0;
}
uni-button[plain] {
color: #353535;
border: 1px solid #353535;
background-color: transparent;
}
uni-button[plain][disabled] {
color: rgba(0, 0, 0, 0.2);
border-color: rgba(0, 0, 0, 0.2);
}
uni-button[plain]:after {
border-width: 0;
}
uni-button[plain][native] .uni-button-cover-view-inner {
padding: 0;
}
uni-button[type='warn'][plain] {
color: #e64340;
border: 1px solid #e64340;
background-color: transparent;
}
uni-button[type='warn'][plain][disabled] {
color: rgba(0, 0, 0, 0.2);
border-color: rgba(0, 0, 0, 0.2);
}
uni-button[type='warn'][plain]:after {
border-width: 0;
}
uni-button[size='mini'] {
display: inline-block;
line-height: 2.3;
font-size: 13px;
padding: 0 1.34em;
}
uni-button[size='mini'][native] {
padding: 0;
}
uni-button[size='mini'][native] .uni-button-cover-view-inner {
padding: 0 1.34em;
}
uni-button[loading]:not([disabled]) {
cursor: progress;
}
uni-button[loading]:before {
content: ' ';
display: inline-block;
width: 18px;
height: 18px;
vertical-align: middle;
animation: uni-loading 1s steps(12, end) infinite;
background-size: 100%;
}
uni-button[loading][type='primary'] {
color: rgba(255, 255, 255, 0.6);
background-color: #0062cc;
}
uni-button[loading][type='primary'][plain] {
color: #007aff;
background-color: transparent;
}
uni-button[loading][type='default'] {
color: rgba(0, 0, 0, 0.6);
background-color: #dedede;
}
uni-button[loading][type='default'][plain] {
color: #353535;
background-color: transparent;
}
uni-button[loading][type='warn'] {
color: rgba(255, 255, 255, 0.6);
background-color: #ce3c39;
}
uni-button[loading][type='warn'][plain] {
color: #e64340;
background-color: transparent;
}
uni-button[loading][native]:before {
content: none;
}
.button-hover {
color: rgba(0, 0, 0, 0.6);
background-color: #dedede;
}
.button-hover[plain] {
color: rgba(53, 53, 53, 0.6);
border-color: rgba(53, 53, 53, 0.6);
background-color: transparent;
}
.button-hover[type='primary'] {
color: rgba(255, 255, 255, 0.6);
background-color: #0062cc;
}
.button-hover[type='primary'][plain] {
color: rgba(26, 173, 25, 0.6);
border-color: rgba(26, 173, 25, 0.6);
background-color: transparent;
}
.button-hover[type='default'] {
color: rgba(0, 0, 0, 0.6);
background-color: #dedede;
}
.button-hover[type='default'][plain] {
color: rgba(53, 53, 53, 0.6);
border-color: rgba(53, 53, 53, 0.6);
background-color: transparent;
}
.button-hover[type='warn'] {
color: rgba(255, 255, 255, 0.6);
background-color: #ce3c39;
}
.button-hover[type='warn'][plain] {
color: rgba(230, 67, 64, 0.6);
border-color: rgba(230, 67, 64, 0.6);
background-color: transparent;
}
export function createServiceContext(Vue, weex, plus, UniServiceJSBridge,instanceContext){
const setTimeout = instanceContext.setTimeout;
const clearTimeout = instanceContext.clearTimeout;
const setInterval = instanceContext.setInterval;
const clearInterval = instanceContext.clearInterval;
const __uniConfig = instanceContext.__uniConfig;
const __uniRoutes = instanceContext.__uniRoutes;
var serviceContext = (function () {
'use strict';
/**
* Make a map and return a function for checking if a key
* is in that map.
* IMPORTANT: all calls of this function must be prefixed with
* \/\*#\_\_PURE\_\_\*\/
* So that rollup can tree-shake them if necessary.
*/
(process.env.NODE_ENV !== 'production')
? Object.freeze({})
: {};
(process.env.NODE_ENV !== 'production') ? Object.freeze([]) : [];
const extend = Object.assign;
const isString = (val) => typeof val === 'string';
let isInitEntryPage = false;
function initEntry() {
if (isInitEntryPage) {
return;
}
isInitEntryPage = true;
let entryPagePath;
let entryPageQuery;
const weexPlus = weex.requireModule('plus');
if (weexPlus.getRedirectInfo) {
const info = weexPlus.getRedirectInfo() || {};
entryPagePath = info.path;
entryPageQuery = info.query ? '?' + info.query : '';
}
else {
const argsJsonStr = plus.runtime.arguments;
if (!argsJsonStr) {
return;
}
try {
const args = JSON.parse(argsJsonStr);
entryPagePath = args.path || args.pathName;
entryPageQuery = args.query ? '?' + args.query : '';
}
catch (e) { }
}
if (!entryPagePath || entryPagePath === __uniConfig.entryPagePath) {
if (entryPageQuery) {
__uniConfig.entryPageQuery = entryPageQuery;
}
return;
}
const entryRoute = '/' + entryPagePath;
const routeOptions = __uniRoutes.find((route) => route.path === entryRoute);
if (!routeOptions) {
return;
}
if (!routeOptions.meta.isTabBar) {
__uniConfig.realEntryPagePath =
__uniConfig.realEntryPagePath || __uniConfig.entryPagePath;
}
__uniConfig.entryPagePath = entryPagePath;
__uniConfig.entryPageQuery = entryPageQuery;
}
const cacheStringFunction = (fn) => {
const cache = Object.create(null);
return ((str) => {
const hit = cache[str];
return hit || (cache[str] = fn(str));
});
};
const invokeArrayFns = (fns, arg) => {
let ret;
for (let i = 0; i < fns.length; i++) {
ret = fns[i](arg);
}
return ret;
};
const TABBAR_HEIGHT = 50;
const SCHEME_RE = /^([a-z-]+:)?\/\//i;
const DATA_RE = /^data:.*,.*/;
const WEB_INVOKE_APPSERVICE = 'WEB_INVOKE_APPSERVICE';
function getRealRoute(fromRoute, toRoute) {
if (toRoute.indexOf('/') === 0) {
return toRoute;
}
if (toRoute.indexOf('./') === 0) {
return getRealRoute(fromRoute, toRoute.substr(2));
}
const toRouteArray = toRoute.split('/');
const toRouteLength = toRouteArray.length;
let i = 0;
for (; i < toRouteLength && toRouteArray[i] === '..'; i++) {
// noop
}
toRouteArray.splice(0, i);
toRoute = toRouteArray.join('/');
const fromRouteArray = fromRoute.length > 0 ? fromRoute.split('/') : [];
fromRouteArray.splice(fromRouteArray.length - i - 1, i + 1);
return '/' + fromRouteArray.concat(toRouteArray).join('/');
}
function getCurrentPage() {
const pages = getCurrentPages();
const len = pages.length;
if (len) {
return pages[len - 1];
}
}
function getCurrentPageVm() {
const page = getCurrentPage();
if (page) {
return page.$vm;
}
}
function invokeHook(vm, name, args) {
if (isString(vm)) {
args = name;
name = vm;
vm = getCurrentPageVm();
}
else if (typeof vm === 'number') {
const page = getCurrentPages().find((page) => page.$page.id === vm);
if (page) {
vm = page.$vm;
}
else {
vm = getCurrentPageVm();
}
}
if (!vm) {
return;
}
const hooks = vm.$[name];
return hooks && invokeArrayFns(hooks, args);
}
function getRealPath(filepath) {
// 无协议的情况补全 https
if (filepath.indexOf('//') === 0) {
return 'https:' + filepath;
}
// 网络资源或base64
if (SCHEME_RE.test(filepath) || DATA_RE.test(filepath)) {
return filepath;
}
if (isSystemURL(filepath)) {
return 'file://' + normalizeLocalPath(filepath);
}
const wwwPath = 'file://' + normalizeLocalPath('_www');
// 绝对路径转换为本地文件系统路径
if (filepath.indexOf('/') === 0) {
// 平台绝对路径 安卓、iOS
if (filepath.startsWith('/storage/') ||
filepath.includes('/Containers/Data/Application/')) {
return 'file://' + filepath;
}
return wwwPath + filepath;
}
// 相对资源
if (filepath.indexOf('../') === 0 || filepath.indexOf('./') === 0) {
// @ts-expect-error app-view
if (typeof __id__ === 'string') {
// @ts-expect-error app-view
return wwwPath + getRealRoute('/' + __id__, filepath);
}
else {
const pages = getCurrentPages();
if (pages.length) {
return (wwwPath + getRealRoute('/' + pages[pages.length - 1].route, filepath));
}
}
}
return filepath;
}
const normalizeLocalPath = cacheStringFunction((filepath) => {
return plus.io
.convertLocalFileSystemURL(filepath)
.replace(/^\/?apps\//, '/android_asset/apps/')
.replace(/\/$/, '');
});
function isSystemURL(filepath) {
if (filepath.indexOf('_www') === 0 ||
filepath.indexOf('_doc') === 0 ||
filepath.indexOf('_documents') === 0 ||
filepath.indexOf('_downloads') === 0) {
return true;
}
return false;
}
const isIOS = plus.os.name === 'iOS';
let config;
/**
* tabbar显示状态
*/
let visible = true;
let tabBar;
/**
* 设置角标
* @param {string} type
* @param {number} index
* @param {string} text
*/
function setTabBarBadge(type, index, text) {
if (!tabBar) {
return;
}
if (type === 'none') {
tabBar.hideTabBarRedDot({
index,
});
tabBar.removeTabBarBadge({
index,
});
}
else if (type === 'text') {
tabBar.setTabBarBadge({
index,
text,
});
}
else if (type === 'redDot') {
tabBar.showTabBarRedDot({
index,
});
}
}
/**
* 动态设置 tabBar 某一项的内容
*/
function setTabBarItem(index, text, iconPath, selectedIconPath) {
const item = {
index,
};
if (text !== undefined) {
item.text = text;
}
if (iconPath) {
item.iconPath = getRealPath(iconPath);
}
if (selectedIconPath) {
item.selectedIconPath = getRealPath(selectedIconPath);
}
tabBar && tabBar.setTabBarItem(item);
}
/**
* 动态设置 tabBar 的整体样式
* @param {Object} style 样式
*/
function setTabBarStyle(style) {
tabBar && tabBar.setTabBarStyle(style);
}
/**
* 隐藏 tabBar
* @param {boolean} animation 是否需要动画效果
*/
function hideTabBar(animation) {
visible = false;
tabBar &&
tabBar.hideTabBar({
animation,
});
}
/**
* 显示 tabBar
* @param {boolean} animation 是否需要动画效果
*/
function showTabBar(animation) {
visible = true;
tabBar &&
tabBar.showTabBar({
animation,
});
}
const maskClickCallback = [];
var tabBar$1 = {
id: '0',
init(options, clickCallback) {
if (options && options.list.length) {
config = options;
}
try {
tabBar = weex.requireModule('uni-tabview');
}
catch (error) {
console.log(`uni.requireNativePlugin("uni-tabview") error ${error}`);
}
tabBar.onMaskClick(() => {
maskClickCallback.forEach((callback) => {
callback();
});
});
tabBar &&
tabBar.onClick(({ index }) => {
clickCallback(config.list[index], index);
});
tabBar &&
tabBar.onMidButtonClick(() => {
// publish('onTabBarMidButtonTap', {})
});
},
indexOf(page) {
const itemLength = config && config.list && config.list.length;
if (itemLength) {
for (let i = 0; i < itemLength; i++) {
if (config.list[i].pagePath === page ||
config.list[i].pagePath === `${page}.html`) {
return i;
}
}
}
return -1;
},
switchTab(page) {
const index = this.indexOf(page);
if (index >= 0) {
tabBar &&
tabBar.switchSelect({
index,
});
return true;
}
return false;
},
setTabBarBadge,
setTabBarItem,
setTabBarStyle,
hideTabBar,
showTabBar,
append(webview) {
tabBar &&
tabBar.append({
id: webview.id,
}, ({ code }) => {
if (code !== 0) {
setTimeout(() => {
this.append(webview);
}, 20);
}
});
},
get visible() {
return visible;
},
get height() {
return ((config && config.height ? parseFloat(config.height) : TABBAR_HEIGHT) +
plus.navigator.getSafeAreaInsets().deviceBottom);
},
// tabBar是否遮挡内容区域
get cover() {
const array = ['extralight', 'light', 'dark'];
return isIOS && array.indexOf(config.blurEffect) >= 0;
},
setStyle({ mask }) {
tabBar.setMask({
color: mask,
});
},
addEventListener(_name, callback) {
maskClickCallback.push(callback);
},
removeEventListener(_name, callback) {
const callbackIndex = maskClickCallback.indexOf(callback);
maskClickCallback.splice(callbackIndex, 1);
},
};
function initTabBar() {
const len = __uniConfig.tabBar?.list?.length;
if (!len) {
return;
}
__uniConfig.tabBar.selectedIndex = 0;
const selected = __uniConfig.tabBar.list.findIndex((page) => page.pagePath === __uniConfig.entryPagePath);
tabBar$1.init(__uniConfig.tabBar, (item, index) => {
uni.switchTab({
url: '/' + item.pagePath,
openType: 'switchTab',
from: 'tabBar',
success() {
invokeHook('onTabItemTap', {
index,
text: item.text,
pagePath: item.pagePath,
});
},
});
});
if (selected !== -1) {
// 取当前 tab 索引值
__uniConfig.tabBar.selectedIndex = selected;
selected !== 0 && tabBar$1.switchTab(__uniConfig.entryPagePath);
}
}
const callbacks = {};
// 简单处理 view 层与 service 层的通知系统
/**
* 消费 view 层通知
*/
function consumePlusMessage(type, args) {
// 处理 web-view 组件发送的通知
if (type === WEB_INVOKE_APPSERVICE) {
UniServiceJSBridge.emit('onWebInvokeAppService', args.data, args.webviewIds);
return true;
}
const callback = callbacks[type];
if (callback) {
callback(args);
if (!callback.keepAlive) {
delete callbacks[type];
}
return true;
}
return false;
}
function backbuttonListener() {
uni.navigateBack({
from: 'backbutton',
});
}
function initGlobalEvent() {
const plusGlobalEvent = plus.weexGlobalEvent;
const weexGlobalEvent = weex.requireModule('weexGlobalEvent');
const emit = UniServiceJSBridge.emit;
if (weex.config.preload) {
plus.key.addEventListener('backbutton', backbuttonListener);
}
else {
plusGlobalEvent.addEventListener('splashclosed', () => {
plus.key.addEventListener('backbutton', backbuttonListener);
});
}
plusGlobalEvent.addEventListener('pause', () => {
emit('onAppEnterBackground');
});
plusGlobalEvent.addEventListener('resume', () => {
emit('onAppEnterForeground');
});
weexGlobalEvent.addEventListener('uistylechange', function (event) {
const args = {
theme: event.uistyle,
};
emit('onThemeChange', args);
});
plusGlobalEvent.addEventListener('plusMessage', onPlusMessage);
// nvue webview post message
plusGlobalEvent.addEventListener('WebviewPostMessage', onPlusMessage);
}
function onPlusMessage(e) {
if (e.data && e.data.type) {
const type = e.data.type;
consumePlusMessage(type, e.data.args || {});
}
}
let appCtx;
const defaultApp = {
globalData: {},
};
function registerApp(appVm) {
appCtx = appVm;
appCtx.$vm = appVm;
extend(appCtx, defaultApp); // 拷贝默认实现
const { $options } = appVm;
if ($options) {
appCtx.globalData = extend($options.globalData || {}, appCtx.globalData);
}
initEntry();
initTabBar();
initGlobalEvent();
}
var index = {
__registerApp: registerApp,
};
return index;
}());
const uni = serviceContext.uni;
const getApp = serviceContext.getApp;
const getCurrentPages = serviceContext.getCurrentPages;
const __definePage = serviceContext.__definePage;
const __registerPage = serviceContext.__registerPage;
return serviceContext;
}
此差异已折叠。
{
"name": "@dcloudio/uni-app-plus",
"version": "3.0.0-alpha-3000020210524001",
"description": "@dcloudio/uni-app-plus",
"files": [
"dist",
"style"
],
"sideEffects": false,
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-app-plus"
},
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/dcloudio/uni-app/issues"
},
"uni-app": {
"name": "uni-app",
"apply": "app"
},
"dependencies": {
"vue3-webcomponent-wrapper": "^0.1.4"
}
}
import { getRealRoute } from '@dcloudio/uni-core'
import { DATA_RE, SCHEME_RE, cacheStringFunction } from '@dcloudio/uni-shared'
export function getRealPath(filepath: string) {
// 无协议的情况补全 https
if (filepath.indexOf('//') === 0) {
return 'https:' + filepath
}
// 网络资源或base64
if (SCHEME_RE.test(filepath) || DATA_RE.test(filepath)) {
return filepath
}
if (isSystemURL(filepath)) {
return 'file://' + normalizeLocalPath(filepath)
}
const wwwPath = 'file://' + normalizeLocalPath('_www')
// 绝对路径转换为本地文件系统路径
if (filepath.indexOf('/') === 0) {
// 平台绝对路径 安卓、iOS
if (
filepath.startsWith('/storage/') ||
filepath.includes('/Containers/Data/Application/')
) {
return 'file://' + filepath
}
return wwwPath + filepath
}
// 相对资源
if (filepath.indexOf('../') === 0 || filepath.indexOf('./') === 0) {
// @ts-expect-error app-view
if (typeof __id__ === 'string') {
// @ts-expect-error app-view
return wwwPath + getRealRoute('/' + __id__, filepath)
} else {
const pages = getCurrentPages()
if (pages.length) {
return (
wwwPath + getRealRoute('/' + pages[pages.length - 1].route, filepath)
)
}
}
}
return filepath
}
const normalizeLocalPath = cacheStringFunction((filepath: string) => {
return plus.io
.convertLocalFileSystemURL(filepath as any)
.replace(/^\/?apps\//, '/android_asset/apps/')
.replace(/\/$/, '')
})
function isSystemURL(filepath: string) {
if (
filepath.indexOf('_www') === 0 ||
filepath.indexOf('_doc') === 0 ||
filepath.indexOf('_documents') === 0 ||
filepath.indexOf('_downloads') === 0
) {
return true
}
return false
}
export function getBaseSystemInfo() {
return {}
}
export function getRealPath() {}
export function operateVideoPlayer() {}
export function operateMap() {}
export function requestComponentInfo() {}
export function addIntersectionObserver() {}
export function removeIntersectionObserver() {}
export function addMediaQueryObserver() {}
export function removeMediaQueryObserver() {}
export function saveImage() {}
export function getSameOriginUrl() {}
export const TEMP_PATH = ''
export const DEVICE_FREQUENCY = 200
export const NETWORK_TYPES = [
'unknown',
'none',
'ethernet',
'wifi',
'2g',
'3g',
'4g',
'5g',
]
export const MAP_ID = '__UNIAPP_MAP'
export const TEMP_PATH_BASE = '_doc/uniapp_temp'
export const TEMP_PATH = `${TEMP_PATH_BASE}_${Date.now()}`
import { ComponentPublicInstance } from 'vue'
import { extend } from '@vue/shared'
import { initEntry } from './initEntry'
import { initTabBar } from './initTabBar'
import { initGlobalEvent } from './initGlobalEvent'
let appCtx: ComponentPublicInstance
const defaultApp = {
globalData: {},
}
export function registerApp(appVm: ComponentPublicInstance) {
appCtx = appVm
appCtx.$vm = appVm
extend(appCtx, defaultApp) // 拷贝默认实现
const { $options } = appVm
if ($options) {
appCtx.globalData = extend($options.globalData || {}, appCtx.globalData)
}
initEntry()
initTabBar()
initGlobalEvent()
}
let isInitEntryPage = false
export function initEntry() {
if (isInitEntryPage) {
return
}
isInitEntryPage = true
let entryPagePath
let entryPageQuery
const weexPlus = weex.requireModule('plus')
if (weexPlus.getRedirectInfo) {
const info = weexPlus.getRedirectInfo() || {}
entryPagePath = info.path
entryPageQuery = info.query ? '?' + info.query : ''
} else {
const argsJsonStr = plus.runtime.arguments
if (!argsJsonStr) {
return
}
try {
const args = JSON.parse(argsJsonStr)
entryPagePath = args.path || args.pathName
entryPageQuery = args.query ? '?' + args.query : ''
} catch (e) {}
}
if (!entryPagePath || entryPagePath === __uniConfig.entryPagePath) {
if (entryPageQuery) {
__uniConfig.entryPageQuery = entryPageQuery
}
return
}
const entryRoute = '/' + entryPagePath
const routeOptions = __uniRoutes.find((route) => route.path === entryRoute)
if (!routeOptions) {
return
}
if (!routeOptions.meta.isTabBar) {
__uniConfig.realEntryPagePath =
__uniConfig.realEntryPagePath || __uniConfig.entryPagePath
}
__uniConfig.entryPagePath = entryPagePath
__uniConfig.entryPageQuery = entryPageQuery
}
import { consumePlusMessage } from './plusMessage'
import { backbuttonListener } from './utils'
export function initGlobalEvent() {
const plusGlobalEvent = (plus as any).weexGlobalEvent
const weexGlobalEvent = weex.requireModule('weexGlobalEvent')
const emit = UniServiceJSBridge.emit
if (weex.config.preload) {
plus.key.addEventListener('backbutton', backbuttonListener)
} else {
plusGlobalEvent.addEventListener('splashclosed', () => {
plus.key.addEventListener('backbutton', backbuttonListener)
})
}
plusGlobalEvent.addEventListener('pause', () => {
emit('onAppEnterBackground')
})
plusGlobalEvent.addEventListener('resume', () => {
emit('onAppEnterForeground')
})
weexGlobalEvent.addEventListener(
'uistylechange',
function (event: { uistyle: string }) {
const args = {
theme: event.uistyle,
}
emit('onThemeChange', args)
}
)
plusGlobalEvent.addEventListener('plusMessage', onPlusMessage)
// nvue webview post message
plusGlobalEvent.addEventListener('WebviewPostMessage', onPlusMessage)
}
function onPlusMessage(e: {
data: { type: string; args: Record<string, any> }
}) {
if (e.data && e.data.type) {
const type = e.data.type
consumePlusMessage(type, e.data.args || {})
}
}
import { invokeHook } from '@dcloudio/uni-core'
import tabBar from './tabBar'
export function initTabBar() {
const len = __uniConfig.tabBar?.list?.length
if (!len) {
return
}
__uniConfig.tabBar!.selectedIndex = 0
const selected = __uniConfig.tabBar!.list.findIndex(
(page) => page.pagePath === __uniConfig.entryPagePath
)
tabBar.init(
__uniConfig.tabBar!,
(item: UniApp.TabBarItemOptions, index: number) => {
uni.switchTab({
url: '/' + item.pagePath,
openType: 'switchTab',
from: 'tabBar',
success() {
invokeHook('onTabItemTap', {
index,
text: item.text,
pagePath: item.pagePath,
})
},
} as UniApp.SwitchTabOptions)
}
)
if (selected !== -1) {
// 取当前 tab 索引值
__uniConfig.tabBar!.selectedIndex = selected
selected !== 0 && tabBar.switchTab(__uniConfig.entryPagePath!)
}
}
import { WEB_INVOKE_APPSERVICE } from '@dcloudio/uni-shared'
interface PlusMessageCallback {
(args: Record<string, any>): void
keepAlive: boolean
}
const callbacks: Record<string, PlusMessageCallback> = {}
// 简单处理 view 层与 service 层的通知系统
/**
* 消费 view 层通知
*/
export function consumePlusMessage(type: string, args: Record<string, any>) {
// 处理 web-view 组件发送的通知
if (type === WEB_INVOKE_APPSERVICE) {
UniServiceJSBridge.emit('onWebInvokeAppService', args.data, args.webviewIds)
return true
}
const callback = callbacks[type]
if (callback) {
callback(args)
if (!callback.keepAlive) {
delete callbacks[type]
}
return true
}
return false
}
/**
* 注册 view 层通知 service 层事件处理
*/
export function registerPlusMessage(
type: string,
callback: PlusMessageCallback,
keepAlive = true
) {
if (callbacks[type]) {
return console.warn(`'${type}' registered: ` + callbacks[type].toString())
}
callback.keepAlive = !!keepAlive
callbacks[type] = callback
}
import { TABBAR_HEIGHT } from '@dcloudio/uni-shared'
import { getRealPath } from '../../../platform/getRealPath'
const isIOS = plus.os.name === 'iOS'
let config: UniApp.TabBarOptions
/**
* tabbar显示状态
*/
let visible = true
let tabBar: any
/**
* 设置角标
* @param {string} type
* @param {number} index
* @param {string} text
*/
function setTabBarBadge(
type: 'none' | 'text' | 'redDot',
index: number,
text: string
) {
if (!tabBar) {
return
}
if (type === 'none') {
tabBar.hideTabBarRedDot({
index,
})
tabBar.removeTabBarBadge({
index,
})
} else if (type === 'text') {
tabBar.setTabBarBadge({
index,
text,
})
} else if (type === 'redDot') {
tabBar.showTabBarRedDot({
index,
})
}
}
/**
* 动态设置 tabBar 某一项的内容
*/
function setTabBarItem(
index: number,
text?: string,
iconPath?: string,
selectedIconPath?: string
) {
const item: Record<string, string | number> = {
index,
}
if (text !== undefined) {
item.text = text
}
if (iconPath) {
item.iconPath = getRealPath(iconPath)
}
if (selectedIconPath) {
item.selectedIconPath = getRealPath(selectedIconPath)
}
tabBar && tabBar.setTabBarItem(item)
}
/**
* 动态设置 tabBar 的整体样式
* @param {Object} style 样式
*/
function setTabBarStyle(style: unknown) {
tabBar && tabBar.setTabBarStyle(style)
}
/**
* 隐藏 tabBar
* @param {boolean} animation 是否需要动画效果
*/
function hideTabBar(animation: boolean) {
visible = false
tabBar &&
tabBar.hideTabBar({
animation,
})
}
/**
* 显示 tabBar
* @param {boolean} animation 是否需要动画效果
*/
function showTabBar(animation: boolean) {
visible = true
tabBar &&
tabBar.showTabBar({
animation,
})
}
const maskClickCallback: Function[] = []
export default {
id: '0',
init(options: UniApp.TabBarOptions, clickCallback: Function) {
if (options && options.list.length) {
config = options
}
try {
tabBar = weex.requireModule('uni-tabview')
} catch (error) {
console.log(`uni.requireNativePlugin("uni-tabview") error ${error}`)
}
tabBar.onMaskClick(() => {
maskClickCallback.forEach((callback) => {
callback()
})
})
tabBar &&
tabBar.onClick(({ index }: { index: number }) => {
clickCallback(config.list[index], index)
})
tabBar &&
tabBar.onMidButtonClick(() => {
// publish('onTabBarMidButtonTap', {})
})
},
indexOf(page: string) {
const itemLength = config && config.list && config.list.length
if (itemLength) {
for (let i = 0; i < itemLength; i++) {
if (
config.list[i].pagePath === page ||
config.list[i].pagePath === `${page}.html`
) {
return i
}
}
}
return -1
},
switchTab(page: string) {
const index = this.indexOf(page)
if (index >= 0) {
tabBar &&
tabBar.switchSelect({
index,
})
return true
}
return false
},
setTabBarBadge,
setTabBarItem,
setTabBarStyle,
hideTabBar,
showTabBar,
append(webview: PlusWebviewWebviewObject) {
tabBar &&
tabBar.append(
{
id: webview.id,
},
({ code }: { code: number }) => {
if (code !== 0) {
setTimeout(() => {
this.append(webview)
}, 20)
}
}
)
},
get visible() {
return visible
},
get height() {
return (
(config && config.height ? parseFloat(config.height) : TABBAR_HEIGHT) +
plus.navigator.getSafeAreaInsets().deviceBottom!
)
},
// tabBar是否遮挡内容区域
get cover() {
const array = ['extralight', 'light', 'dark']
return isIOS && array.indexOf(config.blurEffect as string) >= 0
},
setStyle({ mask }: { mask: string }) {
tabBar.setMask({
color: mask,
})
},
addEventListener(_name: string, callback: Function) {
maskClickCallback.push(callback)
},
removeEventListener(_name: string, callback: Function) {
const callbackIndex = maskClickCallback.indexOf(callback)
maskClickCallback.splice(callbackIndex, 1)
},
}
export function backbuttonListener() {
uni.navigateBack({
from: 'backbutton',
} as UniApp.NavigateBackOptions)
}
import { registerApp as __registerApp } from './framework/app'
export default {
__registerApp,
}
import { createApp, h } from 'vue'
import wrapper from 'vue3-webcomponent-wrapper'
import '@dcloudio/uni-components/style/button.css'
import {
// Audio,
Button,
// Canvas,
// Checkbox,
// CheckboxGroup,
// Editor,
// Form,
Icon,
Image,
// Input,
// Label,
// MovableArea,
// MovableView,
// Navigator,
// PickerView,
// PickerViewColumn,
// Progress,
// Radio,
// RadioGroup,
// ResizeSensor,
// RichText,
// ScrollView,
// Slider,
// Swiper,
// SwiperItem,
// Switch,
Text,
// Textarea,
View,
} from '@dcloudio/uni-components'
const { customElements } = window
customElements.define('v-uni-button', wrapper(Button, createApp, h))
customElements.define('v-uni-icon', wrapper(Icon, createApp, h))
customElements.define('v-uni-image', wrapper(Image, createApp, h))
customElements.define('v-uni-text', wrapper(Text, createApp, h))
customElements.define('v-uni-view', wrapper(View, createApp, h))
import { initView } from '@dcloudio/uni-core'
import path from 'path'
import { defineConfig } from 'vite'
import jscc from 'rollup-plugin-jscc'
import replace from '@rollup/plugin-replace'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { isCustomElement } from '@dcloudio/uni-shared'
function resolve(file: string) {
return path.resolve(__dirname, file)
}
const rollupPlugins = [
replace({
values: {
defineOnApi: `/*#__PURE__*/ defineOnApi`,
defineOffApi: `/*#__PURE__*/ defineOffApi`,
defineTaskApi: `/*#__PURE__*/ defineTaskApi`,
defineSyncApi: `/*#__PURE__*/ defineSyncApi`,
defineAsyncApi: `/*#__PURE__*/ defineAsyncApi`,
__IMPORT_META_ENV_BASE_URL__: 'import.meta.env.BASE_URL', //直接使用import.meta.env.BASE_URL会被vite替换成'/'
},
preventAssignment: true,
}),
jscc({
values: {
// 该插件限制了不能以__开头
_NODE_JS_: 0,
},
// 忽略 pako 内部条件编译
exclude: [resolve('../../node_modules/pako/**')],
}),
]
export default defineConfig({
root: __dirname,
define: {
global: 'window',
__DEV__: true,
__TEST__: false,
__PLATFORM__: JSON.stringify('h5'),
__NODE_JS__: false,
},
resolve: {
alias: [
{
find: '@dcloudio/uni-api',
replacement: resolve('../uni-api/src/index.ts'),
},
{
find: '@dcloudio/uni-vue',
replacement: resolve('../uni-vue/src/index.ts'),
},
{
find: '@dcloudio/uni-core',
replacement: resolve('../uni-core/src'),
},
{
find: '@dcloudio/uni-components/style',
replacement: resolve('../uni-components/style'),
},
{
find: '@dcloudio/uni-components',
replacement: resolve('../uni-components/src/index.ts'),
},
{
find: '@dcloudio/uni-platform',
replacement: resolve('./src/platform/index.ts'),
},
],
},
plugins: [
vue({
template: {
compilerOptions: {
isCustomElement,
},
},
}),
vueJsx({ optimize: true, isCustomElement }),
],
build: {
minify: false,
lib: {
name: 'uni-app-view',
fileName: 'uni-app-view',
entry: path.resolve(__dirname, 'src/view/components/index.ts'),
formats: ['umd'],
},
assetsDir: '.',
rollupOptions: {
output: {
globals: {
vue: 'Vue',
},
},
external(source) {
if (['vue'].includes(source)) {
return true
}
},
preserveEntrySignatures: 'strict',
plugins: rollupPlugins,
onwarn: (msg, warn) => {
if (!String(msg).includes('external module "vue" but never used')) {
warn(msg)
}
},
},
},
})
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
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const mainJs_1 = require("./plugins/mainJs");
const manifestJson_1 = require("./plugins/manifestJson");
const pagesJson_1 = require("./plugins/pagesJson");
const resolveId_1 = require("./plugins/resolveId");
const UniAppPlugin = {
name: 'vite:uni-app',
uni: {
transformEvent: {
tap: 'click',
},
},
};
exports.default = [
resolveId_1.uniResolveIdPlugin(),
mainJs_1.uniMainJsPlugin(),
manifestJson_1.uniManifestJsonPlugin(),
pagesJson_1.uniPagesJsonPlugin(),
UniAppPlugin,
];
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniMainJsPlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function uniMainJsPlugin() {
return uni_cli_shared_1.defineUniMainJsPlugin((opts) => {
return {
name: 'vite:uni-app-main-js',
enforce: 'pre',
transform(code, id) {
if (opts.filter(id)) {
code = code.includes('createSSRApp')
? createApp(code)
: createLegacyApp(code);
return {
code,
map: this.getCombinedSourcemap(),
};
}
},
};
});
}
exports.uniMainJsPlugin = uniMainJsPlugin;
function createApp(code) {
return `createApp().app.mount("#app");${code.replace('createSSRApp', 'createVueApp as createSSRApp')}`;
}
function createLegacyApp(code) {
return `function createApp(rootComponent,rootProps){return createVueApp(rootComponent, rootProps)};${code.replace('createApp', 'createVueApp')}`;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniManifestJsonPlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const defaultRouter = {
mode: 'hash',
base: '/',
};
const defaultAsync = {
loading: 'AsyncLoading',
error: 'AsyncError',
delay: 200,
timeout: 60000,
suspensible: true,
};
const defaultNetworkTimeout = {
request: 60000,
connectSocket: 60000,
uploadFile: 60000,
downloadFile: 60000,
};
const defaultQQMapKey = 'XVXBZ-NDMC4-JOGUS-XGIEE-QVHDZ-AMFV2';
function uniManifestJsonPlugin() {
return uni_cli_shared_1.defineUniManifestJsonPlugin((opts) => {
return {
name: 'vite:uni-app-manifest-json',
enforce: 'pre',
transform(code, id) {
if (!opts.filter(id)) {
return;
}
const manifest = JSON.parse(code);
const { debug, h5 } = manifest;
const appid = (manifest.appid || '').replace('__UNI__', '');
const router = Object.assign(Object.assign({}, defaultRouter), ((h5 && h5.router) || {}));
if (!router.base) {
router.base = '/';
}
const async = Object.assign(Object.assign({}, defaultAsync), ((h5 && h5.async) || {}));
const networkTimeout = Object.assign(Object.assign({}, defaultNetworkTimeout), (manifest.networkTimeout || {}));
const sdkConfigs = (h5 && h5.sdkConfigs) || {};
const qqMapKey = (sdkConfigs.maps &&
sdkConfigs.maps.qqmap &&
sdkConfigs.maps.qqmap.key) ||
defaultQQMapKey;
const flexDirection = (manifest['app'] &&
manifest['app'].nvue &&
manifest['app'].nvue['flex-direction']) ||
'column';
return {
code: `export const appid = '${appid || ''}'
export const debug = ${!!debug}
export const nvue = ${JSON.stringify({
'flex-direction': flexDirection,
})}
export const networkTimeout = ${JSON.stringify(networkTimeout)}
// h5
export const router = ${JSON.stringify(router)}
export const async = ${JSON.stringify(async)}
export const qqMapKey = '${qqMapKey}'
export const sdkConfigs = ${JSON.stringify(sdkConfigs)}
`,
map: { mappings: '' },
};
},
};
});
}
exports.uniManifestJsonPlugin = uniManifestJsonPlugin;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniPagesJsonPlugin = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const slash_1 = __importDefault(require("slash"));
const shared_1 = require("@vue/shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const pkg = require('@dcloudio/vite-plugin-uni/package.json');
function uniPagesJsonPlugin() {
return uni_cli_shared_1.defineUniPagesJsonPlugin((opts) => {
return {
name: 'vite:uni-app-pages-json',
enforce: 'pre',
transform(code, id, ssr) {
if (opts.filter(id)) {
const { resolvedConfig } = opts;
return {
code: (resolvedConfig.command === 'serve' ||
(resolvedConfig.command === 'build' && ssr)
? registerGlobalCode(resolvedConfig, ssr)
: '') + generatePagesJsonCode(ssr, code, resolvedConfig),
map: { mappings: '' },
};
}
},
};
});
}
exports.uniPagesJsonPlugin = uniPagesJsonPlugin;
function generatePagesJsonCode(ssr, jsonStr, config) {
const globalName = getGlobal(ssr);
const pagesJson = uni_cli_shared_1.normalizePagesJson(jsonStr, process.env.UNI_INPUT_DIR, process.env.UNI_PLATFORM);
const { importLayoutComponentsCode, defineLayoutComponentsCode } = generateLayoutComponentsCode(globalName, pagesJson);
const definePagesCode = generatePagesDefineCode(pagesJson, config);
const uniRoutesCode = generateRoutes(globalName, pagesJson, config);
const uniConfigCode = generateConfig(globalName, pagesJson, config);
const manifestJsonPath = slash_1.default(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'manifest.json.js'));
const cssCode = generateCssCode(config);
return `
import { defineAsyncComponent, resolveComponent, createVNode, withCtx, openBlock, createBlock } from 'vue'
import { PageComponent, AsyncLoadingComponent, AsyncErrorComponent } from '@dcloudio/uni-h5'
import { appid, debug, networkTimeout, router, async, sdkConfigs, qqMapKey, nvue } from '${manifestJsonPath}'
${importLayoutComponentsCode}
const extend = Object.assign
${cssCode}
${uniConfigCode}
${defineLayoutComponentsCode}
${definePagesCode}
${uniRoutesCode}
${config.command === 'serve' ? hmrCode : ''}
export {}
`;
}
const hmrCode = `if(import.meta.hot){
import.meta.hot.on('invalidate', (data) => {
import.meta.hot.invalidate()
})
}`;
function getGlobal(ssr) {
return ssr ? 'global' : 'window';
}
function registerGlobalCode(config, ssr) {
const name = getGlobal(ssr);
const rpx2pxCode = !ssr && config.define.__UNI_FEATURE_RPX__
? `import {upx2px} from '@dcloudio/uni-h5'
${name}.rpx2px = upx2px
`
: '';
return `${rpx2pxCode}
import {uni,getCurrentPages,getApp,UniServiceJSBridge,UniViewJSBridge} from '@dcloudio/uni-h5'
${name}.getApp = getApp
${name}.getCurrentPages = getCurrentPages
${name}.uni = uni
${name}.UniViewJSBridge = UniViewJSBridge
${name}.UniServiceJSBridge = UniServiceJSBridge
`;
}
function normalizePageIdentifier(path) {
return shared_1.capitalize(shared_1.camelize(path.replace(/\//g, '-')));
}
function generateCssCode(config) {
const define = config.define;
const cssFiles = [uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'base.css'];
// if (define.__UNI_FEATURE_PAGES__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'async.css');
// }
if (define.__UNI_FEATURE_RESPONSIVE__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'layout.css');
}
if (define.__UNI_FEATURE_NAVIGATIONBAR__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'pageHead.css');
}
if (define.__UNI_FEATURE_TABBAR__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'tabBar.css');
}
if (define.__UNI_FEATURE_NVUE__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'nvue.css');
}
if (define.__UNI_FEATURE_PULL_DOWN_REFRESH__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'pageRefresh.css');
}
if (define.__UNI_FEATURE_NAVIGATIONBAR_SEARCHINPUT__) {
cssFiles.push(uni_cli_shared_1.BASE_COMPONENTS_STYLE_PATH + 'input.css');
}
if (config.command === 'serve') {
// 开发模式,自动添加所有API相关css
Object.keys(uni_cli_shared_1.API_DEPS_CSS).forEach((name) => {
const styles = uni_cli_shared_1.API_DEPS_CSS[name];
styles.forEach((style) => {
if (!cssFiles.includes(style)) {
cssFiles.push(style);
}
});
});
}
return cssFiles.map((file) => `import '${file}'`).join('\n');
}
function generateLayoutComponentsCode(globalName, pagesJson) {
const windowNames = [
'topWindow',
'leftWindow',
'rightWindow',
];
let importLayoutComponentsCode = '';
let defineLayoutComponentsCode = `${globalName}.__uniLayout = ${globalName}.__uniLayout || {}\n`;
windowNames.forEach((name) => {
const windowConfig = pagesJson[name];
if (windowConfig && windowConfig.path) {
importLayoutComponentsCode += `import ${name} from './${windowConfig.path}'\n`;
defineLayoutComponentsCode += `${globalName}.__uniConfig.${name}.component = ${name}\n`;
}
});
return {
importLayoutComponentsCode,
defineLayoutComponentsCode,
};
}
function generatePageDefineCode(pageOptions) {
const pageIdent = normalizePageIdentifier(pageOptions.path);
return `const ${pageIdent}Loader = ()=>import('./${pageOptions.path}?mpType=page')
const ${pageIdent} = defineAsyncComponent(extend({loader:${pageIdent}Loader},AsyncComponentOptions))`;
}
function generatePagesDefineCode(pagesJson, _config) {
const { pages } = pagesJson;
return (`const AsyncComponentOptions = {
loadingComponent: AsyncLoadingComponent,
errorComponent: AsyncErrorComponent,
delay: async.delay,
timeout: async.timeout,
suspensible: async.suspensible
}
` + pages.map((pageOptions) => generatePageDefineCode(pageOptions)).join('\n'));
}
function normalizePagesRoute(pagesJson) {
const firstPagePath = pagesJson.pages[0].path;
const tabBarList = (pagesJson.tabBar && pagesJson.tabBar.list) || [];
return pagesJson.pages.map((pageOptions) => {
const pagePath = pageOptions.path;
const name = normalizePageIdentifier(pagePath);
const isEntry = firstPagePath === pagePath ? true : undefined;
const tabBarIndex = tabBarList.findIndex((tabBarPage) => tabBarPage.pagePath === pagePath);
const isTabBar = tabBarIndex !== -1 ? true : undefined;
const isNVue = fs_1.default.existsSync(path_1.default.join(process.env.UNI_INPUT_DIR, pagePath + '.nvue'));
let windowTop = 0;
const meta = shared_1.extend({
route: pageOptions.path,
isNVue: isNVue ? true : undefined,
isQuit: isEntry || isTabBar ? true : undefined,
isEntry,
isTabBar,
tabBarIndex,
windowTop,
}, pageOptions.style);
return {
name,
path: pageOptions.path,
meta,
};
});
}
function generatePageRoute({ name, path, meta }, config) {
const { isEntry } = meta;
const alias = isEntry ? `\n alias:'/${path}',` : '';
return `{
path:'/${isEntry ? '' : path}',${alias}
component:{setup(){return ()=>renderPage(${name})}},
loader: ${normalizePageIdentifier(path)}Loader,
meta: ${JSON.stringify(meta)}
}`;
}
function generatePagesRoute(pagesRouteOptions, config) {
return pagesRouteOptions.map((pageOptions) => generatePageRoute(pageOptions, config));
}
function generateRoutes(globalName, pagesJson, config) {
return `
function renderPage(component){
return (openBlock(), createBlock(PageComponent, null, {page: withCtx(() => [createVNode(component, { ref: "page" }, null, 512 /* NEED_PATCH */)]), _: 1 /* STABLE */}))
}
${globalName}.__uniRoutes=[${[
...generatePagesRoute(normalizePagesRoute(pagesJson), config),
].join(',')}]`;
}
function generateConfig(globalName, pagesJson, config) {
delete pagesJson.pages;
delete pagesJson.subPackages;
delete pagesJson.subpackages;
pagesJson.compilerVersion = pkg['uni-app'].compilerVersion;
return ((config.command === 'serve'
? ''
: `${globalName}['____'+appid+'____']=true
delete ${globalName}['____'+appid+'____']
`) +
`${globalName}.__uniConfig=extend(${JSON.stringify(pagesJson)},{
async,
debug,
networkTimeout,
sdkConfigs,
qqMapKey,
nvue,
router
})
`);
}
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniResolveIdPlugin = void 0;
const path_1 = __importDefault(require("path"));
const debug_1 = __importDefault(require("debug"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const debugResolve = debug_1.default('vite:uni:resolve');
function uniResolveIdPlugin() {
const resolveCache = {};
return {
name: 'vite:uni-app-resolve-id',
enforce: 'pre',
configResolved() {
const { MODE } = uni_cli_shared_1.parseCompatConfigOnce(process.env.UNI_INPUT_DIR);
resolveCache['@dcloudio/uni-h5'] = uni_cli_shared_1.resolveBuiltIn(path_1.default.join('@dcloudio/uni-h5', 'dist/uni-h5.es.js'));
resolveCache['@dcloudio/uni-h5-vue'] = uni_cli_shared_1.resolveBuiltIn(path_1.default.join('@dcloudio/uni-h5-vue', `dist/vue.runtime.${MODE === 2 ? 'compat.' : ''}esm.js`));
},
resolveId(id) {
if (id === 'vue') {
id = '@dcloudio/uni-h5-vue';
}
const cache = resolveCache[id];
if (cache) {
debugResolve('cache', id, cache);
return cache;
}
if (id.startsWith('@dcloudio/uni-h5/style') ||
id.startsWith('@dcloudio/uni-components/style')) {
return (resolveCache[id] = uni_cli_shared_1.resolveBuiltIn(id));
}
},
};
}
exports.uniResolveIdPlugin = uniResolveIdPlugin;
{
"name": "@dcloudio/uni-app-vite",
"version": "3.0.0-alpha-3000020210528002",
"description": "uni-app-vite",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist/**/*.js",
"dist/**/*.d.ts"
],
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-app-vite"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"uni-app": {
"name": "uni-app-plus",
"apply": "app",
"main": "dist/index.js"
},
"license": "Apache-2.0"
}
import { UniVitePlugin } from '@dcloudio/uni-cli-shared'
import { uniMainJsPlugin } from './plugins/mainJs'
import { uniManifestJsonPlugin } from './plugins/manifestJson'
import { uniPagesJsonPlugin } from './plugins/pagesJson'
import { uniResolveIdPlugin } from './plugins/resolveId'
const UniAppPlugin: UniVitePlugin = {
name: 'vite:uni-app',
uni: {
transformEvent: {
tap: 'click',
},
},
}
export default [
uniResolveIdPlugin(),
uniMainJsPlugin(),
uniManifestJsonPlugin(),
uniPagesJsonPlugin(),
UniAppPlugin,
]
import { defineUniMainJsPlugin } from '@dcloudio/uni-cli-shared'
export function uniMainJsPlugin() {
return defineUniMainJsPlugin((opts) => {
return {
name: 'vite:uni-app-main-js',
enforce: 'pre',
transform(code, id) {
if (opts.filter(id)) {
code = code.includes('createSSRApp')
? createApp(code)
: createLegacyApp(code)
return {
code,
map: this.getCombinedSourcemap(),
}
}
},
}
})
}
function createApp(code: string) {
return `createApp().app.mount("#app");${code.replace(
'createSSRApp',
'createVueApp as createSSRApp'
)}`
}
function createLegacyApp(code: string) {
return `function createApp(rootComponent,rootProps){return createVueApp(rootComponent, rootProps)};${code.replace(
'createApp',
'createVueApp'
)}`
}
import { Plugin } from 'vite'
import { defineUniManifestJsonPlugin } from '@dcloudio/uni-cli-shared'
const defaultRouter = {
mode: 'hash',
base: '/',
}
const defaultAsync = {
loading: 'AsyncLoading',
error: 'AsyncError',
delay: 200,
timeout: 60000,
suspensible: true,
}
const defaultNetworkTimeout = {
request: 60000,
connectSocket: 60000,
uploadFile: 60000,
downloadFile: 60000,
}
const defaultQQMapKey = 'XVXBZ-NDMC4-JOGUS-XGIEE-QVHDZ-AMFV2'
export function uniManifestJsonPlugin(): Plugin {
return defineUniManifestJsonPlugin((opts) => {
return {
name: 'vite:uni-app-manifest-json',
enforce: 'pre',
transform(code, id) {
if (!opts.filter(id)) {
return
}
const manifest = JSON.parse(code)
const { debug, h5 } = manifest
const appid = (manifest.appid || '').replace('__UNI__', '')
const router = { ...defaultRouter, ...((h5 && h5.router) || {}) }
if (!router.base) {
router.base = '/'
}
const async = { ...defaultAsync, ...((h5 && h5.async) || {}) }
const networkTimeout = {
...defaultNetworkTimeout,
...(manifest.networkTimeout || {}),
}
const sdkConfigs = (h5 && h5.sdkConfigs) || {}
const qqMapKey =
(sdkConfigs.maps &&
sdkConfigs.maps.qqmap &&
sdkConfigs.maps.qqmap.key) ||
defaultQQMapKey
const flexDirection =
(manifest['app'] &&
manifest['app'].nvue &&
manifest['app'].nvue['flex-direction']) ||
'column'
return {
code: `export const appid = '${appid || ''}'
export const debug = ${!!debug}
export const nvue = ${JSON.stringify({
'flex-direction': flexDirection,
})}
export const networkTimeout = ${JSON.stringify(networkTimeout)}
// h5
export const router = ${JSON.stringify(router)}
export const async = ${JSON.stringify(async)}
export const qqMapKey = '${qqMapKey}'
export const sdkConfigs = ${JSON.stringify(sdkConfigs)}
`,
map: { mappings: '' },
}
},
}
})
}
import fs from 'fs'
import path from 'path'
import slash from 'slash'
import { Plugin, ResolvedConfig } from 'vite'
import { extend, camelize, capitalize } from '@vue/shared'
import {
API_DEPS_CSS,
FEATURE_DEFINES,
H5_FRAMEWORK_STYLE_PATH,
BASE_COMPONENTS_STYLE_PATH,
normalizePagesJson,
defineUniPagesJsonPlugin,
} from '@dcloudio/uni-cli-shared'
const pkg = require('@dcloudio/vite-plugin-uni/package.json')
export function uniPagesJsonPlugin(): Plugin {
return defineUniPagesJsonPlugin((opts) => {
return {
name: 'vite:uni-app-pages-json',
enforce: 'pre',
transform(code, id, ssr) {
if (opts.filter(id)) {
const { resolvedConfig } = opts
return {
code:
(resolvedConfig.command === 'serve' ||
(resolvedConfig.command === 'build' && ssr)
? registerGlobalCode(resolvedConfig, ssr)
: '') + generatePagesJsonCode(ssr, code, resolvedConfig),
map: { mappings: '' },
}
}
},
}
})
}
interface PageRouteOptions {
name: string
path: string
meta: Partial<UniApp.PageRouteMeta>
}
function generatePagesJsonCode(
ssr: boolean | undefined,
jsonStr: string,
config: ResolvedConfig
) {
const globalName = getGlobal(ssr)
const pagesJson = normalizePagesJson(
jsonStr,
process.env.UNI_INPUT_DIR,
process.env.UNI_PLATFORM
)
const { importLayoutComponentsCode, defineLayoutComponentsCode } =
generateLayoutComponentsCode(globalName, pagesJson)
const definePagesCode = generatePagesDefineCode(pagesJson, config)
const uniRoutesCode = generateRoutes(globalName, pagesJson, config)
const uniConfigCode = generateConfig(globalName, pagesJson, config)
const manifestJsonPath = slash(
path.resolve(process.env.UNI_INPUT_DIR, 'manifest.json.js')
)
const cssCode = generateCssCode(config)
return `
import { defineAsyncComponent, resolveComponent, createVNode, withCtx, openBlock, createBlock } from 'vue'
import { PageComponent, AsyncLoadingComponent, AsyncErrorComponent } from '@dcloudio/uni-h5'
import { appid, debug, networkTimeout, router, async, sdkConfigs, qqMapKey, nvue } from '${manifestJsonPath}'
${importLayoutComponentsCode}
const extend = Object.assign
${cssCode}
${uniConfigCode}
${defineLayoutComponentsCode}
${definePagesCode}
${uniRoutesCode}
${config.command === 'serve' ? hmrCode : ''}
export {}
`
}
const hmrCode = `if(import.meta.hot){
import.meta.hot.on('invalidate', (data) => {
import.meta.hot.invalidate()
})
}`
function getGlobal(ssr?: boolean) {
return ssr ? 'global' : 'window'
}
function registerGlobalCode(config: ResolvedConfig, ssr?: boolean) {
const name = getGlobal(ssr)
const rpx2pxCode =
!ssr && config.define!.__UNI_FEATURE_RPX__
? `import {upx2px} from '@dcloudio/uni-h5'
${name}.rpx2px = upx2px
`
: ''
return `${rpx2pxCode}
import {uni,getCurrentPages,getApp,UniServiceJSBridge,UniViewJSBridge} from '@dcloudio/uni-h5'
${name}.getApp = getApp
${name}.getCurrentPages = getCurrentPages
${name}.uni = uni
${name}.UniViewJSBridge = UniViewJSBridge
${name}.UniServiceJSBridge = UniServiceJSBridge
`
}
function normalizePageIdentifier(path: string) {
return capitalize(camelize(path.replace(/\//g, '-')))
}
function generateCssCode(config: ResolvedConfig) {
const define = config.define! as FEATURE_DEFINES
const cssFiles = [H5_FRAMEWORK_STYLE_PATH + 'base.css']
// if (define.__UNI_FEATURE_PAGES__) {
cssFiles.push(H5_FRAMEWORK_STYLE_PATH + 'async.css')
// }
if (define.__UNI_FEATURE_RESPONSIVE__) {
cssFiles.push(H5_FRAMEWORK_STYLE_PATH + 'layout.css')
}
if (define.__UNI_FEATURE_NAVIGATIONBAR__) {
cssFiles.push(H5_FRAMEWORK_STYLE_PATH + 'pageHead.css')
}
if (define.__UNI_FEATURE_TABBAR__) {
cssFiles.push(H5_FRAMEWORK_STYLE_PATH + 'tabBar.css')
}
if (define.__UNI_FEATURE_NVUE__) {
cssFiles.push(H5_FRAMEWORK_STYLE_PATH + 'nvue.css')
}
if (define.__UNI_FEATURE_PULL_DOWN_REFRESH__) {
cssFiles.push(H5_FRAMEWORK_STYLE_PATH + 'pageRefresh.css')
}
if (define.__UNI_FEATURE_NAVIGATIONBAR_SEARCHINPUT__) {
cssFiles.push(BASE_COMPONENTS_STYLE_PATH + 'input.css')
}
if (config.command === 'serve') {
// 开发模式,自动添加所有API相关css
Object.keys(API_DEPS_CSS).forEach((name) => {
const styles = API_DEPS_CSS[name as keyof typeof API_DEPS_CSS]
styles.forEach((style) => {
if (!cssFiles.includes(style)) {
cssFiles.push(style)
}
})
})
}
return cssFiles.map((file) => `import '${file}'`).join('\n')
}
function generateLayoutComponentsCode(
globalName: string,
pagesJson: UniApp.PagesJson
) {
const windowNames: Array<'topWindow' | 'leftWindow' | 'rightWindow'> = [
'topWindow',
'leftWindow',
'rightWindow',
]
let importLayoutComponentsCode = ''
let defineLayoutComponentsCode = `${globalName}.__uniLayout = ${globalName}.__uniLayout || {}\n`
windowNames.forEach((name) => {
const windowConfig = pagesJson[name]
if (windowConfig && windowConfig.path) {
importLayoutComponentsCode += `import ${name} from './${windowConfig.path}'\n`
defineLayoutComponentsCode += `${globalName}.__uniConfig.${name}.component = ${name}\n`
}
})
return {
importLayoutComponentsCode,
defineLayoutComponentsCode,
}
}
function generatePageDefineCode(pageOptions: UniApp.PagesJsonPageOptions) {
const pageIdent = normalizePageIdentifier(pageOptions.path)
return `const ${pageIdent}Loader = ()=>import('./${pageOptions.path}?mpType=page')
const ${pageIdent} = defineAsyncComponent(extend({loader:${pageIdent}Loader},AsyncComponentOptions))`
}
function generatePagesDefineCode(
pagesJson: UniApp.PagesJson,
_config: ResolvedConfig
) {
const { pages } = pagesJson
return (
`const AsyncComponentOptions = {
loadingComponent: AsyncLoadingComponent,
errorComponent: AsyncErrorComponent,
delay: async.delay,
timeout: async.timeout,
suspensible: async.suspensible
}
` + pages.map((pageOptions) => generatePageDefineCode(pageOptions)).join('\n')
)
}
function normalizePagesRoute(pagesJson: UniApp.PagesJson): PageRouteOptions[] {
const firstPagePath = pagesJson.pages[0].path
const tabBarList = (pagesJson.tabBar && pagesJson.tabBar.list) || []
return pagesJson.pages.map((pageOptions) => {
const pagePath = pageOptions.path
const name = normalizePageIdentifier(pagePath)
const isEntry = firstPagePath === pagePath ? true : undefined
const tabBarIndex = tabBarList.findIndex(
(tabBarPage: { pagePath: string }) => tabBarPage.pagePath === pagePath
)
const isTabBar = tabBarIndex !== -1 ? true : undefined
const isNVue = fs.existsSync(
path.join(process.env.UNI_INPUT_DIR, pagePath + '.nvue')
)
let windowTop = 0
const meta = extend(
{
route: pageOptions.path,
isNVue: isNVue ? true : undefined,
isQuit: isEntry || isTabBar ? true : undefined,
isEntry,
isTabBar,
tabBarIndex,
windowTop,
},
pageOptions.style
)
return {
name,
path: pageOptions.path,
meta,
}
})
}
function generatePageRoute(
{ name, path, meta }: PageRouteOptions,
config: ResolvedConfig
) {
const { isEntry } = meta
const alias = isEntry ? `\n alias:'/${path}',` : ''
return `{
path:'/${isEntry ? '' : path}',${alias}
component:{setup(){return ()=>renderPage(${name})}},
loader: ${normalizePageIdentifier(path)}Loader,
meta: ${JSON.stringify(meta)}
}`
}
function generatePagesRoute(
pagesRouteOptions: PageRouteOptions[],
config: ResolvedConfig
) {
return pagesRouteOptions.map((pageOptions) =>
generatePageRoute(pageOptions, config)
)
}
function generateRoutes(
globalName: string,
pagesJson: UniApp.PagesJson,
config: ResolvedConfig
) {
return `
function renderPage(component){
return (openBlock(), createBlock(PageComponent, null, {page: withCtx(() => [createVNode(component, { ref: "page" }, null, 512 /* NEED_PATCH */)]), _: 1 /* STABLE */}))
}
${globalName}.__uniRoutes=[${[
...generatePagesRoute(normalizePagesRoute(pagesJson), config),
].join(',')}]`
}
function generateConfig(
globalName: string,
pagesJson: Record<string, any>,
config: ResolvedConfig
) {
delete pagesJson.pages
delete pagesJson.subPackages
delete pagesJson.subpackages
pagesJson.compilerVersion = pkg['uni-app'].compilerVersion
return (
(config.command === 'serve'
? ''
: `${globalName}['____'+appid+'____']=true
delete ${globalName}['____'+appid+'____']
`) +
`${globalName}.__uniConfig=extend(${JSON.stringify(pagesJson)},{
async,
debug,
networkTimeout,
sdkConfigs,
qqMapKey,
nvue,
router
})
`
)
}
import path from 'path'
import debug from 'debug'
import { Plugin } from 'vite'
import { resolveBuiltIn, parseCompatConfigOnce } from '@dcloudio/uni-cli-shared'
const debugResolve = debug('vite:uni:resolve')
export function uniResolveIdPlugin(): Plugin {
const resolveCache: Record<string, string> = {}
return {
name: 'vite:uni-app-resolve-id',
enforce: 'pre',
configResolved() {
const { MODE } = parseCompatConfigOnce(process.env.UNI_INPUT_DIR)
resolveCache['@dcloudio/uni-h5'] = resolveBuiltIn(
path.join('@dcloudio/uni-h5', 'dist/uni-h5.es.js')
)
resolveCache['@dcloudio/uni-h5-vue'] = resolveBuiltIn(
path.join(
'@dcloudio/uni-h5-vue',
`dist/vue.runtime.${MODE === 2 ? 'compat.' : ''}esm.js`
)
)
},
resolveId(id) {
if (id === 'vue') {
id = '@dcloudio/uni-h5-vue'
}
const cache = resolveCache[id]
if (cache) {
debugResolve('cache', id, cache)
return cache
}
if (
id.startsWith('@dcloudio/uni-h5/style') ||
id.startsWith('@dcloudio/uni-components/style')
) {
return (resolveCache[id] = resolveBuiltIn(id))
}
},
}
}
{
"extends": "../../tsconfig.node.json",
"compilerOptions": {
"outDir": "dist"
},
"include": ["src", "../shims-node.d.ts", "../shims-uni-app.d.ts"]
}
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
{
"input": {
"src/index.ts": ["dist/vue.runtime.esm.js"]
}
}
此差异已折叠。
此差异已折叠。
{
"name": "@dcloudio/uni-app-vue",
"version": "3.0.0-alpha-3000020210528002",
"description": "@dcloudio/uni-app-vue",
"main": "dist/vue.runtime.esm.js",
"module": "dist/vue.runtime.esm.js",
"files": [
"dist"
],
"sideEffects": false,
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-app-vue"
},
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/dcloudio/uni-app/issues"
},
"gitHead": "0eff378978e778420c7d2bfc9b039a387d15aac9"
}
export * from '../lib/vue.runtime.esm'
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册