初始化

This commit is contained in:
yziiy
2025-08-11 11:06:07 +08:00
parent 083bc37c00
commit 5607d11395
19772 changed files with 3108723 additions and 18 deletions

View File

@@ -0,0 +1,202 @@
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.

View File

@@ -0,0 +1,2 @@
declare const _default: () => import("vite").Plugin[];
export default _default;

View File

@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const vue_1 = require("./vue");
const nvue_1 = require("./nvue");
const plugin_1 = require("./plugin");
exports.default = () => {
return [
(0, plugin_1.uniAppPlugin)({
renderer: process.env.UNI_RENDERER,
appService: process.env.UNI_RENDERER_NATIVE === 'appService',
}),
(0, uni_cli_shared_1.uniUTSAppPlugin)({
x: false,
extApis: (0, uni_cli_shared_1.parseUniExtApiNamespacesOnce)(process.env.UNI_UTS_PLATFORM, process.env.UNI_UTS_TARGET_LANGUAGE),
}),
...(process.env.UNI_COMPILER === 'nvue'
? (0, nvue_1.initNVuePlugins)()
: (0, vue_1.initVuePlugins)()),
];
};

View File

@@ -0,0 +1,2 @@
export { initNVueNodeTransforms } from './plugin';
export declare function initNVuePlugins(): import("vite").Plugin[];

View File

@@ -0,0 +1,34 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initNVuePlugins = exports.initNVueNodeTransforms = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const easycom_1 = require("../plugins/easycom");
const manifestJson_1 = require("../plugins/manifestJson");
const stats_1 = require("../plugins/stats");
const template_1 = require("../plugins/template");
const plugin_1 = require("./plugin");
const appCss_1 = require("./plugins/appCss");
const esbuild_1 = require("./plugins/esbuild");
const mainJs_1 = require("./plugins/mainJs");
const pagesJson_1 = require("./plugins/pagesJson");
const renderjs_1 = require("./plugins/renderjs");
var plugin_2 = require("./plugin");
Object.defineProperty(exports, "initNVueNodeTransforms", { enumerable: true, get: function () { return plugin_2.initNVueNodeTransforms; } });
function initNVuePlugins() {
const renderer = process.env.UNI_RENDERER;
const appService = process.env.UNI_RENDERER_NATIVE === 'appService';
return [
(0, appCss_1.uniAppCssPlugin)(),
(0, easycom_1.uniEasycomPlugin)({ exclude: uni_cli_shared_1.UNI_EASYCOM_EXCLUDE }),
(0, uni_cli_shared_1.uniHBuilderXConsolePlugin)(),
(0, mainJs_1.uniMainJsPlugin)({ renderer, appService }),
(0, manifestJson_1.uniManifestJsonPlugin)(),
(0, pagesJson_1.uniPagesJsonPlugin)({ renderer, appService }),
(0, uni_cli_shared_1.uniViteInjectPlugin)('uni:app-inject', (0, uni_cli_shared_1.initAppProvide)()),
(0, renderjs_1.uniRenderjsPlugin)(),
(0, plugin_1.uniAppNVuePlugin)({ appService }),
(0, esbuild_1.uniEsbuildPlugin)({ renderer, appService }),
...(appService ? [(0, stats_1.uniStatsPlugin)(), (0, template_1.uniTemplatePlugin)({ renderer })] : []),
];
}
exports.initNVuePlugins = initNVuePlugins;

View File

@@ -0,0 +1,9 @@
import type { Plugin } from 'vite';
export declare function initNVueNodeTransforms(): import("@vue/compiler-core").NodeTransform[];
export declare function initNVueDirectiveTransforms(): {
model: import("@vue/compiler-core").DirectiveTransform;
show: import("@vue/compiler-core").DirectiveTransform;
};
export declare function uniAppNVuePlugin({ appService, }: {
appService: boolean;
}): Plugin;

View File

@@ -0,0 +1,153 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniAppNVuePlugin = exports.initNVueDirectiveTransforms = exports.initNVueNodeTransforms = void 0;
const path_1 = __importDefault(require("path"));
const picocolors_1 = __importDefault(require("picocolors"));
const uni_shared_1 = require("@dcloudio/uni-shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const uni_nvue_styler_1 = require("@dcloudio/uni-nvue-styler");
const utils_1 = require("../../utils");
// import { transformRenderWhole } from './transforms/transformRenderWhole'
// import { transformAppendAsTree } from './transforms/transformAppendAsTree'
const transformVideo_1 = require("./transforms/transformVideo");
const transformText_1 = require("./transforms/transformText");
const configResolved_1 = require("../../plugin/configResolved");
const utils_2 = require("../utils");
const transformRootNode_1 = require("./transforms/transformRootNode");
const vModel_1 = require("./transforms/vModel");
const vShow_1 = require("./transforms/vShow");
const transformAttrs_1 = require("./transforms/transformAttrs");
const pagesJson_1 = require("../plugins/pagesJson");
const transformUTSComponent_1 = require("./transforms/transformUTSComponent");
const uTags = {
text: 'u-text',
image: 'u-image',
input: 'u-input',
textarea: 'u-textarea',
video: 'u-video',
'web-view': 'u-web-view',
slider: 'u-slider',
};
function initNVueNodeTransforms() {
// 优先级必须确保 renderWhole > appendAsTree
return [
transformRootNode_1.transformRootNode,
(0, uni_cli_shared_1.createTransformTag)(uTags),
transformAttrs_1.transformAttrs,
transformText_1.transformText,
transformVideo_1.transformVideo,
transformUTSComponent_1.transformUTSComponent,
// transformRenderWhole,
// transformAppendAsTree,
];
}
exports.initNVueNodeTransforms = initNVueNodeTransforms;
function initNVueDirectiveTransforms() {
return {
model: vModel_1.transformModel,
show: vShow_1.transformShow,
};
}
exports.initNVueDirectiveTransforms = initNVueDirectiveTransforms;
function uniAppNVuePlugin({ appService, }) {
const inputDir = process.env.UNI_INPUT_DIR;
const mainPath = (0, uni_cli_shared_1.resolveMainPathOnce)(inputDir);
return {
name: 'uni:app-nvue',
config() {
return {
css: {
postcss: {
plugins: (0, uni_cli_shared_1.initPostcssPlugin)({
uniApp: uni_shared_1.defaultNVueRpx2Unit,
autoprefixer: false,
}),
},
},
build: {
lib: {
name: 'AppService',
// 必须使用 lib 模式,否则会生成 preload 等代码
fileName: appService ? 'app-service' : 'app',
entry: mainPath,
formats: [appService ? 'iife' : 'es'],
},
outDir: appService ? process.env.UNI_OUTPUT_DIR : (0, utils_1.nvueOutDir)(),
rollupOptions: {
external: (0, utils_2.external)(appService),
output: {
entryFileNames(chunk) {
if (chunk.name === 'main' && chunk.isEntry) {
return appService ? uni_cli_shared_1.APP_SERVICE_FILENAME : 'app.js';
}
return chunk.name + '.js';
},
chunkFileNames: createChunkFileNames(inputDir),
plugins: [(0, uni_cli_shared_1.dynamicImportPolyfill)(true)],
globals: (0, utils_2.globals)(appService),
},
},
},
};
},
configResolved: (0, configResolved_1.createConfigResolved)({
createCssPostPlugin(config) {
return {
name: 'vite:css-post',
buildStart() {
// 用于覆盖原始插件方法
// noop
},
async transform(source, filename) {
if (!uni_cli_shared_1.cssLangRE.test(filename) || uni_cli_shared_1.commonjsProxyRE.test(filename)) {
return;
}
const nvuePages = pagesJson_1.nvuePagesCache.get(config);
if (!nvuePages || !Object.keys(nvuePages).length) {
// 当前项目没有 nvue 文件
return { code: `export default {}`, map: { mappings: '' } };
}
const { code, messages } = await (0, uni_nvue_styler_1.parse)(source, {
filename,
logLevel: 'WARNING',
});
messages.forEach((message) => {
if (message.type === 'warning') {
config.logger.warn(picocolors_1.default.yellow(`[plugin:vite:nvue-css] ${message.text}`));
let msg = '';
if (message.line && message.column) {
msg += `\n${(0, uni_cli_shared_1.generateCodeFrame)(source, {
line: message.line,
column: message.column,
})}\n`;
}
msg += `${(0, uni_cli_shared_1.formatAtFilename)(filename)}`;
config.logger.warn(msg);
}
});
return { code: `export default ${code}`, map: { mappings: '' } };
},
generateBundle() {
// 用于覆盖原始插件方法
// noop
},
};
},
}),
};
}
exports.uniAppNVuePlugin = uniAppNVuePlugin;
function createChunkFileNames(inputDir) {
return function chunkFileNames(chunk) {
if (chunk.isDynamicEntry && chunk.facadeModuleId) {
const { filename } = (0, uni_cli_shared_1.parseVueRequest)(chunk.facadeModuleId);
if (filename.endsWith('.nvue')) {
return ((0, uni_cli_shared_1.removeExt)((0, uni_cli_shared_1.normalizePath)(path_1.default.relative(inputDir, filename))) + '.js');
}
}
return '[name].js';
};
}

View File

@@ -0,0 +1,11 @@
import { CompilerError, SourceLocation } from '@vue/compiler-core';
export declare const enum NVueErrorCodes {
X_V_SHOW = 0,
X_V_MODEL_DYNAMIC_TYPE = 1,
X_V_MODEL_AND_V_BIND = 2
}
interface NVueCompilerError extends CompilerError {
code: NVueErrorCodes;
}
export declare function createNVueCompilerError(code: NVueErrorCodes, loc?: SourceLocation, additionalMessage?: string): NVueCompilerError;
export {};

View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNVueCompilerError = void 0;
const compiler_core_1 = require("@vue/compiler-core");
const NVueErrorMessages = {
[0 /* NVueErrorCodes.X_V_SHOW */]: 'nvue: v-show is not supported',
[1 /* NVueErrorCodes.X_V_MODEL_DYNAMIC_TYPE */]: 'nvue: v-model with :type="" is not supported',
[2 /* NVueErrorCodes.X_V_MODEL_AND_V_BIND */]: 'nvue: v-model with v-bind is not supported',
};
function createNVueCompilerError(code, loc, additionalMessage) {
return (0, compiler_core_1.createCompilerError)(code, loc, NVueErrorMessages, additionalMessage);
}
exports.createNVueCompilerError = createNVueCompilerError;

View File

@@ -0,0 +1,2 @@
import { NodeTransform } from '@vue/compiler-core';
export declare const transformAppendAsTree: NodeTransform;

View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformAppendAsTree = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const compiler_core_1 = require("@vue/compiler-core");
const unitaryTags = [
'cell',
'header',
'cell-slot',
'recycle-list',
'text',
'u-text',
];
const transformAppendAsTree = (node, _) => {
if (!(0, uni_cli_shared_1.isElementNode)(node)) {
return;
}
// append => appendAsTree: true
const appendProp = (0, compiler_core_1.findProp)(node, 'append');
if (appendProp) {
(0, uni_cli_shared_1.renameProp)('appendAsTree', appendProp);
return;
}
if (!unitaryTags.includes(node.tag)) {
return;
}
node.props.push((0, uni_cli_shared_1.createBindDirectiveNode)('appendAsTree', 'true'));
};
exports.transformAppendAsTree = transformAppendAsTree;

View File

@@ -0,0 +1,8 @@
import { NodeTransform } from '@vue/compiler-core';
/**
* 将内置组件属性调整为驼峰
* @param node
* @param context
* @returns
*/
export declare const transformAttrs: NodeTransform;

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformAttrs = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const uni_shared_1 = require("@dcloudio/uni-shared");
const shared_1 = require("@vue/shared");
/**
* 将内置组件属性调整为驼峰
* @param node
* @param context
* @returns
*/
const transformAttrs = (node, context) => {
if (!(0, uni_cli_shared_1.isElementNode)(node)) {
return;
}
if (!(0, uni_shared_1.isAppNVueNativeTag)(node.tag)) {
return;
}
node.props.forEach((prop) => {
if ((0, uni_cli_shared_1.isDirectiveNode)(prop)) {
const { arg } = prop;
if (arg && (0, uni_cli_shared_1.isSimpleExpressionNode)(arg)) {
arg.content = normalizePropName(arg.content);
}
}
else {
prop.name = normalizePropName(prop.name);
}
});
};
exports.transformAttrs = transformAttrs;
function normalizePropName(name) {
if (name.startsWith('data-')) {
return name;
}
return (0, shared_1.camelize)(name);
}

View File

@@ -0,0 +1,7 @@
import { NodeTransform, RootNode } from '@vue/compiler-core';
export declare const transformRenderWhole: NodeTransform;
/**
* 仅当根节点只有一个,标签在白名单,且开发者未主动配置的情况下,才补充
* @param node
*/
export declare function addRenderWhole(node: RootNode): void;

View File

@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addRenderWhole = exports.transformRenderWhole = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const compiler_core_1 = require("@vue/compiler-core");
const transformRenderWhole = (node, _) => {
if (!(0, uni_cli_shared_1.isElementNode)(node)) {
return;
}
const prop = (0, compiler_core_1.findProp)(node, 'render-whole');
if (!prop) {
return;
}
// render-whole => append
(0, uni_cli_shared_1.renameProp)('append', prop);
};
exports.transformRenderWhole = transformRenderWhole;
//
const RENDER_WHOLE_TAGS = [
'view',
'scroll-view',
'swiper',
'match-media',
'movable-area',
'movable-view',
'cover-view',
'cover-image',
'form',
'picker',
'picker-view',
'navigator',
'map',
];
/**
* 仅当根节点只有一个,标签在白名单,且开发者未主动配置的情况下,才补充
* @param node
*/
function addRenderWhole(node) {
if (node.children.length === 1) {
const element = node.children[0];
if ((0, uni_cli_shared_1.isElementNode)(element) && RENDER_WHOLE_TAGS.includes(element.tag)) {
if (!(0, compiler_core_1.findProp)(element, 'render-whole') &&
!(0, compiler_core_1.findProp)(element, 'append') &&
!(0, compiler_core_1.findProp)(element, 'appendAsTree')) {
element.props.push((0, uni_cli_shared_1.createBindDirectiveNode)('render-whole', (0, compiler_core_1.createSimpleExpression)('true')));
}
}
}
}
exports.addRenderWhole = addRenderWhole;

View File

@@ -0,0 +1,2 @@
import { NodeTransform } from '@vue/compiler-core';
export declare const transformRootNode: NodeTransform;

View File

@@ -0,0 +1,76 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformRootNode = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const compiler_core_1 = require("@vue/compiler-core");
const transformRenderWhole_1 = require("./transformRenderWhole");
const SCROLLER_COMPONENTS = [
'list',
'scroller',
'scroll-view',
'waterfall',
'recycle-list',
];
const transformRootNode = (node, context) => {
if (node.type !== 0 /* NodeTypes.ROOT */) {
return;
}
const isPage = !!context.bindingMetadata.__pageOptions;
if (!isPage) {
// 非页面组件,自动为根节点补充 render-whole
return (0, transformRenderWhole_1.addRenderWhole)(node);
}
const { disableScroll, scrollIndicator } = context.bindingMetadata
.__pageOptions;
// 禁用滚动,或已包含滚动元素
if (disableScroll || hasScrollerElement(node)) {
return wrapperByView(node);
}
return wrapperByScrollView(node, { scrollIndicator });
};
exports.transformRootNode = transformRootNode;
function hasScrollerElement(node) {
return node.children.some((child) => {
if (child.type === 1 /* NodeTypes.ELEMENT */) {
return SCROLLER_COMPONENTS.includes(child.tag);
}
});
}
function wrapperByScrollView(node, { scrollIndicator }) {
node.children = [
createElement('scroll-view', createScrollViewProps({ scrollIndicator }), node.children),
];
}
const trueExpr = (0, compiler_core_1.createSimpleExpression)('true');
const falseExpr = (0, compiler_core_1.createSimpleExpression)('false');
function createScrollViewProps({ scrollIndicator, }) {
return [
(0, uni_cli_shared_1.createBindDirectiveNode)('scrollY', trueExpr),
(0, uni_cli_shared_1.createBindDirectiveNode)('showScrollbar', scrollIndicator === 'none' ? falseExpr : trueExpr),
(0, uni_cli_shared_1.createBindDirectiveNode)('enableBackToTop', trueExpr),
(0, uni_cli_shared_1.createAttributeNode)('bubble', 'true'),
(0, uni_cli_shared_1.createBindDirectiveNode)('style', `{flexDirection:'column'}`),
];
}
/**
* 目前暂不支持多节点,故发现多节点时,自动补充一个 view 根节点
* @param node
*/
function wrapperByView(node) {
if (node.children.length > 1) {
node.children = [createElement('view', [], node.children)];
}
}
function createElement(tag, props, children) {
return {
type: 1 /* NodeTypes.ELEMENT */,
ns: 0,
tag,
isSelfClosing: false,
props,
children,
tagType: 0 /* ElementTypes.ELEMENT */,
codegenNode: undefined,
loc: compiler_core_1.locStub,
};
}

View File

@@ -0,0 +1,2 @@
import { NodeTransform } from '@vue/compiler-core';
export declare const transformText: NodeTransform;

View File

@@ -0,0 +1,99 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformText = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function isTextNode({ tag }) {
return tag === 'text' || tag === 'u-text' || tag === 'button';
}
function isTextElement(node) {
return node.type === 1 /* NodeTypes.ELEMENT */ && node.tag === 'text';
}
function isText(node) {
const { type } = node;
return (type === 2 /* NodeTypes.TEXT */ ||
type === 12 /* NodeTypes.TEXT_CALL */ ||
type === 5 /* NodeTypes.INTERPOLATION */ ||
type === 8 /* NodeTypes.COMPOUND_EXPRESSION */);
}
const transformText = (node, _) => {
if (!(0, uni_cli_shared_1.isElementNode)(node)) {
return;
}
if (isTextNode(node)) {
return;
}
const { children } = node;
if (!children.length) {
return;
}
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (isTextElement(child)) {
parseText(child);
}
let currentContainer = undefined;
if (isText(child)) {
if (!currentContainer) {
currentContainer = children[i] = createText(node, child);
}
for (let j = i + 1; j < children.length; j++) {
const next = children[j];
if (isText(next)) {
// 合并相邻的文本节点
currentContainer.children.push(next);
children.splice(j, 1);
j--;
}
else {
currentContainer = undefined;
break;
}
}
}
}
};
exports.transformText = transformText;
/*
1. 转换 \\n 为 \n
2. u-text 下只能有一个文本节点(不支持 children需要移除子组件并合并文本
*/
function parseText(node) {
if (node.children.length) {
let firstTextChild;
for (let i = 0; i < node.children.length; i++) {
const child = node.children[i];
if (isText(child) && typeof child.content === 'string') {
if (!firstTextChild) {
firstTextChild = child;
firstTextChild.content = firstTextChild.content.replace(/\\n/g, '\n');
}
else {
;
firstTextChild.content += child.content.replace(/\\n/g, '\n');
node.children.splice(i, 1);
i--;
}
}
else if (child.type === 1 || child.type === 3) {
node.children.splice(i, 1);
i--;
}
else {
firstTextChild = null;
}
}
}
}
function createText(parent, node) {
return {
tag: 'u-text',
type: 1 /* NodeTypes.ELEMENT */,
tagType: 0 /* ElementTypes.ELEMENT */,
props: [],
isSelfClosing: false,
children: [node],
codegenNode: undefined,
ns: parent.ns,
loc: node.loc,
};
}

View File

@@ -0,0 +1,8 @@
import { NodeTransform } from '@vue/compiler-core';
/**
* 将uts组件保存到自定义组件列表中
* @param node
* @param context
* @returns
*/
export declare const transformUTSComponent: NodeTransform;

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformUTSComponent = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../../utils");
/**
* 将uts组件保存到自定义组件列表中
* @param node
* @param context
* @returns
*/
const transformUTSComponent = (node, context) => {
if (!(0, uni_cli_shared_1.isElementNode)(node)) {
return;
}
if ((0, utils_1.isUTSComponent)(node.tag)) {
if (!context.root.components.includes(node.tag)) {
context.components.add(node.tag);
}
}
};
exports.transformUTSComponent = transformUTSComponent;

View File

@@ -0,0 +1,2 @@
import { NodeTransform } from '@vue/compiler-core';
export declare const transformVideo: NodeTransform;

View File

@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformVideo = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const compiler_core_1 = require("@vue/compiler-core");
function isVideo(node) {
return node.tag === 'video' || node.tag === 'u-video';
}
const transformVideo = (node, _) => {
if (!(0, uni_cli_shared_1.isElementNode)(node)) {
return;
}
if (!isVideo(node)) {
return;
}
if (!node.children.length) {
return;
}
const firstChild = node.children[0];
if ((0, uni_cli_shared_1.isElementNode)(firstChild) && firstChild.tag === 'u-scalable') {
return;
}
node.children = [createScalable(node)];
};
exports.transformVideo = transformVideo;
function createScalable(node) {
return {
tag: 'u-scalable',
type: 1 /* NodeTypes.ELEMENT */,
tagType: 0 /* ElementTypes.ELEMENT */,
props: [
(0, uni_cli_shared_1.createBindDirectiveNode)('style', (0, compiler_core_1.createSimpleExpression)('{position:"absolute",left:"0",right:"0",top:"0",bottom:"0"}')),
],
isSelfClosing: true,
children: node.children,
codegenNode: undefined,
ns: node.ns,
loc: node.loc,
};
}

View File

@@ -0,0 +1,2 @@
import { DirectiveTransform } from '@vue/compiler-core';
export declare const transformModel: DirectiveTransform;

View File

@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformModel = void 0;
const compiler_core_1 = require("@vue/compiler-core");
const shared_1 = require("@vue/shared");
const tags = ['u-input', 'u-textarea'];
const transformModel = (dir, node, context) => {
const result = (0, compiler_core_1.transformModel)(dir, node, context);
// 将 u-input,u-textarea 的 onUpdate:modelValue 事件转换为 onInput
if (tags.includes(node.tag) && result.props.length >= 2) {
const key = result.props[1].key;
let value = result.props[1].value;
if (value.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */) {
value = value.value;
}
if ((0, compiler_core_1.isStaticExp)(key) &&
key.content === 'onUpdate:modelValue' &&
value.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
key.content = 'onInput';
// 替换 $event 为 $event.detail.value
value.children = value.children.map((child) => {
if ((0, shared_1.isString)(child)) {
return child.replace(/=\s\$event/g, `= $event.detail.value`);
}
return child;
});
}
}
return result;
};
exports.transformModel = transformModel;

View File

@@ -0,0 +1,2 @@
import { DirectiveTransform } from '@vue/compiler-core';
export declare const transformShow: DirectiveTransform;

View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformShow = void 0;
const errors_1 = require("./errors");
const transformShow = (dir, node, context) => {
context.onError((0, errors_1.createNVueCompilerError)(0 /* NVueErrorCodes.X_V_SHOW */, dir.loc));
return {
props: [],
};
};
exports.transformShow = transformShow;

View File

@@ -0,0 +1,11 @@
import type { Plugin } from 'vite';
import type { RollupError } from 'rollup';
import { CompilerError } from '@vue/compiler-sfc';
declare module '@vue/compiler-sfc' {
interface SFCDescriptor {
id: string;
}
}
export declare const APP_CSS_JS = "./app.css.js";
export declare function uniAppCssPlugin(): Plugin;
export declare function createRollupError(id: string, error: CompilerError | SyntaxError): RollupError;

View File

@@ -0,0 +1,132 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createRollupError = exports.uniAppCssPlugin = exports.APP_CSS_JS = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
exports.APP_CSS_JS = './app.css.js';
function uniAppCssPlugin() {
const inputDir = process.env.UNI_INPUT_DIR;
const appVueFilename = (0, uni_cli_shared_1.resolveAppVue)(inputDir);
return {
name: 'uni:app-nvue-app-style',
// 提前到 @vite/plugin-vue 之前执行,因为在 nvue 编译时,仅 import 了 App.vue 的 styles这样导致 descriptor
// 一直使用的是上一次的plugin-vue 会在 transformMain 中生成新的 descriptor故不再交由 plugin-vue 来 load
// 而是当前插件直接处理
enforce: 'pre',
resolveId(id) {
if (id === exports.APP_CSS_JS) {
return exports.APP_CSS_JS;
}
},
load(id) {
if (id === exports.APP_CSS_JS) {
return genAppStylesCode(appVueFilename, this);
}
const { filename, query } = (0, uni_cli_shared_1.parseVueRequest)(id);
if (query.vue && query.type === 'style' && appVueFilename === filename) {
const descriptor = createAppDescriptor(filename, this);
const block = descriptor.styles[query.index];
if (block) {
return {
code: block.content,
map: '',
};
}
}
},
};
}
exports.uniAppCssPlugin = uniAppCssPlugin;
const defaultAppStylesCode = `exports.styles = []`;
async function genAppStylesCode(filename, pluginContext) {
pluginContext.addWatchFile(filename);
const descriptor = createAppDescriptor(filename, pluginContext);
if (!descriptor.styles.length) {
return defaultAppStylesCode;
}
let stylesCode = ``;
const styleVars = [];
for (let i = 0; i < descriptor.styles.length; i++) {
const style = descriptor.styles[i];
const src = style.src || descriptor.filename;
const attrsQuery = attrsToQuery(style.attrs, 'css');
const srcQuery = style.src ? `&src=${descriptor.id}` : ``;
const query = `?vue&type=style&index=${i}${srcQuery}&inline`;
const styleRequest = src + query + attrsQuery;
stylesCode += `\nimport _style_${i} from ${JSON.stringify(styleRequest)}`;
styleVars.push(`_style_${i}`);
}
return `
${stylesCode}
exports.styles = [${styleVars.join(',')}]
`;
}
function readAppCode(filename) {
if (!fs_extra_1.default.existsSync(filename)) {
return ``;
}
const source = fs_extra_1.default.readFileSync(filename, 'utf8');
if (source.includes('#endif')) {
return (0, uni_cli_shared_1.preNVueJs)((0, uni_cli_shared_1.preNVueHtml)(source));
}
return source;
}
let appDescriptor;
function createAppDescriptor(filename, pluginContext) {
const source = readAppCode(filename);
const id = (0, uni_cli_shared_1.hash)(source);
if (!appDescriptor || appDescriptor.id !== id) {
const { descriptor, errors } = require('@vue/compiler-sfc').parse(source, {
filename,
});
descriptor.id = id;
if (errors.length) {
errors.forEach((error) => pluginContext.error(createRollupError(filename, error)));
}
appDescriptor = descriptor;
}
return appDescriptor;
}
function createRollupError(id, error) {
const { message, name, stack } = error;
const rollupError = {
id,
plugin: 'vue',
message,
name,
stack,
};
if ('code' in error && error.loc) {
rollupError.loc = {
file: id,
line: error.loc.start.line,
column: error.loc.start.column,
};
}
return rollupError;
}
exports.createRollupError = createRollupError;
// these are built-in query parameters so should be ignored
// if the user happen to add them as attrs
const ignoreList = ['id', 'index', 'src', 'type', 'lang', 'module'];
function attrsToQuery(attrs, langFallback, forceLangFallback = false) {
let query = ``;
for (const name in attrs) {
const value = attrs[name];
if (!ignoreList.includes(name)) {
query += `&${encodeURIComponent(name)}${value ? `=${encodeURIComponent(value)}` : ``}`;
}
}
if (langFallback || attrs.lang) {
query +=
`lang` in attrs
? forceLangFallback
? `&lang.${langFallback}`
: `&lang.${attrs.lang}`
: `&lang.${langFallback}`;
}
return query;
}

View File

@@ -0,0 +1,6 @@
import type { Plugin } from 'vite';
export declare function uniEsbuildPlugin({ appService, }: {
renderer?: 'native';
appService: boolean;
}): Plugin;
export declare function wrapperNVueAppStyles(code: string): string;

View File

@@ -0,0 +1,161 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.wrapperNVueAppStyles = exports.uniEsbuildPlugin = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const debug_1 = __importDefault(require("debug"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../../utils");
const utils_2 = require("../utils");
const appCss_1 = require("./appCss");
const debugEsbuild = (0, debug_1.default)('uni:app-nvue-esbuild');
const emittedHashMap = new WeakMap();
function uniEsbuildPlugin({ appService, }) {
let resolvedConfig;
let buildOptions;
const nvueOutputDir = (0, utils_1.nvueOutDir)();
const outputDir = process.env.UNI_OUTPUT_DIR;
let isFirst = true;
return {
name: 'uni:app-nvue-esbuild',
enforce: 'post',
configResolved(config) {
buildOptions = {
format: 'iife',
target: 'es6',
minify: config.build.minify ? true : false,
banner: {
js: `"use weex:vue";
${uni_cli_shared_1.polyfillCode}`,
},
bundle: true,
write: false,
plugins: [esbuildGlobalPlugin((0, utils_2.esbuildGlobals)(appService))],
};
resolvedConfig = config;
emittedHashMap.set(resolvedConfig, new Map());
},
async writeBundle(_, bundle) {
const entryPoints = [];
const assets = [];
Object.keys(bundle).forEach((name) => {
const chunk = bundle[name];
if (chunk.type === 'chunk' &&
chunk.facadeModuleId &&
chunk.facadeModuleId.endsWith('.nvue')) {
entryPoints.push(name);
}
else if (chunk.type === 'asset') {
assets.push(name);
}
});
// 仅 nvueOutputDir 时 copy
if (!appService) {
assets.forEach((name) => {
fs_extra_1.default.copySync(path_1.default.resolve(nvueOutputDir, name), path_1.default.resolve(outputDir, name), { overwrite: false });
});
}
if (!entryPoints.length) {
return;
}
const emittedHash = emittedHashMap.get(resolvedConfig);
const changedFiles = [];
if (buildAppCss()) {
changedFiles.push(uni_cli_shared_1.APP_CONFIG_SERVICE);
}
debugEsbuild('start', entryPoints.length, entryPoints);
for (const filename of entryPoints) {
await buildNVuePage(filename, buildOptions).then((code) => {
const outputFileHash = (0, uni_cli_shared_1.hash)(code);
if (emittedHash.get(filename) !== outputFileHash) {
changedFiles.push(filename);
emittedHash.set(filename, outputFileHash);
return fs_extra_1.default.outputFile(path_1.default.resolve(outputDir, filename), code);
}
});
}
if (!isFirst && changedFiles.length) {
process.env[changedFiles.includes(uni_cli_shared_1.APP_CONFIG_SERVICE)
? 'UNI_APP_CHANGED_FILES'
: 'UNI_APP_CHANGED_PAGES'] = JSON.stringify(changedFiles);
}
debugEsbuild('end');
isFirst = false;
},
};
}
exports.uniEsbuildPlugin = uniEsbuildPlugin;
/**
* 将 nvue 全局 css 样式注入 app-config-service.js
* @returns
*/
function buildAppCss() {
const appCssJsFilename = path_1.default.join((0, utils_1.nvueOutDir)(), appCss_1.APP_CSS_JS);
if (!fs_extra_1.default.existsSync(appCssJsFilename)) {
return;
}
const appCssJsCode = fs_extra_1.default.readFileSync(appCssJsFilename, 'utf8');
const appCssJsFn = new Function('module', appCssJsCode.replace(`export default`, `module.exports=`));
const module = { exports: { styles: [] } };
appCssJsFn(module);
const appCssJsonCode = JSON.stringify(module.exports.styles);
if (process.env.UNI_NVUE_APP_STYLES === appCssJsonCode) {
return;
}
process.env.UNI_NVUE_APP_STYLES = appCssJsonCode;
// 首次 build 时,可能还没生成 app-config-service 的文件,故仅写入环境变量
const appConfigServiceFilename = path_1.default.join(process.env.UNI_OUTPUT_DIR, uni_cli_shared_1.APP_CONFIG_SERVICE);
if (!fs_extra_1.default.existsSync(appConfigServiceFilename)) {
return;
}
const appConfigServiceCode = fs_extra_1.default.readFileSync(appConfigServiceFilename, 'utf8');
fs_extra_1.default.writeFileSync(appConfigServiceFilename, wrapperNVueAppStyles(appConfigServiceCode));
return true;
}
function buildNVuePage(filename, options) {
return (0, uni_cli_shared_1.transformWithEsbuild)(`import App from './${filename}'
const webview = plus.webview.currentWebview()
if(webview){
const __pageId = parseInt(webview.id)
const __pagePath = '${(0, uni_cli_shared_1.removeExt)(filename)}'
let __pageQuery = {}
try{ __pageQuery = JSON.parse(webview.__query__) }catch(e){}
App.mpType = 'page'
const app = Vue.createPageApp(App,{$store:getApp({allowDefault:true}).$store,__pageId,__pagePath,__pageQuery})
app.provide('__globalStyles', Vue.useCssStyles([...__uniConfig.styles, ...(App.styles||[])]))
app.mount('#root')
}`, path_1.default.join((0, utils_1.nvueOutDir)(), 'main.js'), options).then((res) => {
if (res.outputFiles) {
return res.outputFiles[0].text;
}
return '';
});
}
function esbuildGlobalPlugin(options) {
const keys = Object.keys(options);
return {
name: 'global',
setup(build) {
keys.forEach((key) => {
const namespace = key + '-ns';
build.onResolve({ filter: new RegExp('^' + key + '$') }, ({ path }) => {
return {
path,
namespace,
};
});
build.onLoad({ filter: /.*/, namespace }, () => ({
contents: `module.exports = ${options[key]}`,
loader: 'js',
}));
});
},
};
}
function wrapperNVueAppStyles(code) {
return code.replace(/__uniConfig.styles=(.*);\/\/styles/, `__uniConfig.styles=${process.env.UNI_NVUE_APP_STYLES || '[]'};//styles`);
}
exports.wrapperNVueAppStyles = wrapperNVueAppStyles;

View File

@@ -0,0 +1,4 @@
export declare function uniMainJsPlugin({ renderer, appService, }: {
renderer?: 'native';
appService: boolean;
}): import("vite").Plugin;

View File

@@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniMainJsPlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const appCss_1 = require("./appCss");
function uniMainJsPlugin({ renderer, appService, }) {
return (0, uni_cli_shared_1.defineUniMainJsPlugin)((opts) => {
return {
name: 'uni:app-nvue-main-js',
enforce: 'pre',
transform(code, id) {
if (opts.filter(id)) {
if (renderer !== 'native') {
return {
code: `import './${uni_cli_shared_1.PAGES_JSON_JS}';import('${appCss_1.APP_CSS_JS}').then(()=>{})`,
map: { mappings: '' },
};
}
if (appService) {
code = code.includes('createSSRApp')
? createApp(code)
: createLegacyApp(code);
return {
code: `import './${uni_cli_shared_1.MANIFEST_JSON_JS}';\nimport './${uni_cli_shared_1.PAGES_JSON_JS}';\n` +
code,
map: { mappings: '' },
};
}
return {
code: `import './${uni_cli_shared_1.PAGES_JSON_JS}';`,
map: { mappings: '' },
};
}
},
};
});
}
exports.uniMainJsPlugin = uniMainJsPlugin;
function createApp(code) {
return `${code.replace('createSSRApp', 'createVueApp as createSSRApp')};const {app:__app__,Vuex:__Vuex__,Pinia:__Pinia__}=createApp();uni.Vuex=__Vuex__;uni.Pinia=__Pinia__;__app__._component.mpType='app';__app__._component.render=()=>{};__app__.mount('#app');`;
}
function createLegacyApp(code) {
return `function createApp(rootComponent,rootProps){rootComponent.mpTye='app';rootComponent.render=()=>{};const app=createVueApp(rootComponent,rootProps);const oldMount=app.mount;app.mount=(container)=>{const appVm=oldMount.call(app,container);return appVm;};return app;};${code.replace('createApp', 'createVueApp')}`;
}

View File

@@ -0,0 +1,43 @@
import type { Plugin } from 'vite';
interface NVuePages {
[filename: string]: {
disableScroll?: boolean;
scrollIndicator?: 'none';
};
}
export declare const nvuePagesCache: Map<Readonly<Omit<import("vite").UserConfig, "plugins" | "assetsInclude" | "optimizeDeps" | "worker"> & {
configFile: string | undefined;
configFileDependencies: string[];
inlineConfig: import("vite").InlineConfig;
root: string;
base: string;
publicDir: string;
cacheDir: string;
command: "build" | "serve";
mode: string;
isWorker: boolean;
isProduction: boolean;
envDir: string;
env: Record<string, any>;
resolve: Required<import("vite").ResolveOptions> & {
alias: import("vite").Alias[];
};
plugins: readonly Plugin[];
esbuild: false | import("vite").ESBuildOptions;
server: import("vite").ResolvedServerOptions;
build: import("vite").ResolvedBuildOptions;
preview: import("vite").ResolvedPreviewOptions;
ssr: import("vite").ResolvedSSROptions;
assetsInclude: (file: string) => boolean;
logger: import("vite").Logger;
createResolver: (options?: Partial<import("vite").InternalResolveOptions> | undefined) => import("vite").ResolveFn;
optimizeDeps: import("vite").DepOptimizationOptions;
worker: import("vite").ResolveWorkerOptions;
appType: import("vite").AppType;
experimental: import("vite").ExperimentalOptions;
} & import("vite").PluginHookUtils>, NVuePages>;
export declare function uniPagesJsonPlugin({ renderer, appService, }: {
renderer?: 'native';
appService: boolean;
}): Plugin;
export {};

View File

@@ -0,0 +1,79 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniPagesJsonPlugin = exports.nvuePagesCache = void 0;
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
exports.nvuePagesCache = new Map();
// 在 @vue/compiler-sfc@3.2.47 执行前重写 @vue/compiler-dom compile 方法
const nvuePages = {};
rewriteBindingMetadata(nvuePages);
function uniPagesJsonPlugin({ renderer, appService, }) {
return (0, uni_cli_shared_1.defineUniPagesJsonPlugin)((opts) => {
return {
name: 'uni:app-nvue-pages-json',
enforce: 'pre',
configResolved(config) {
exports.nvuePagesCache.set(config, nvuePages);
},
transform(code, id) {
if (!opts.filter(id)) {
return;
}
this.addWatchFile(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'pages.json'));
(0, uni_cli_shared_1.getLocaleFiles)(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'locale')).forEach((filepath) => {
this.addWatchFile(filepath);
});
const pagesJson = (0, uni_cli_shared_1.normalizePagesJson)(code, process.env.UNI_PLATFORM);
Object.keys(nvuePages).forEach((name) => {
delete nvuePages[name];
});
pagesJson.pages.forEach((page) => {
if (page.style.isNVue) {
const filename = (0, uni_cli_shared_1.normalizePath)(path_1.default.resolve(process.env.UNI_INPUT_DIR, page.path + '.nvue'));
nvuePages[filename] = {
disableScroll: page.style.disableScroll,
scrollIndicator: page.style.scrollIndicator,
};
// fix: question/164673
// this.addWatchFile(filename)
}
});
if (renderer === 'native' && appService) {
this.emitFile({
fileName: uni_cli_shared_1.APP_CONFIG_SERVICE,
type: 'asset',
source: (0, uni_cli_shared_1.normalizeAppConfigService)(pagesJson, (0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR)),
});
return {
code: '',
map: { mappings: '' },
};
}
return {
code: (0, uni_cli_shared_1.normalizeAppNVuePagesJson)(pagesJson),
map: { mappings: '' },
};
},
};
});
}
exports.uniPagesJsonPlugin = uniPagesJsonPlugin;
/**
* 在 BindingMetadata 中补充页面标记
*/
function rewriteBindingMetadata(nvuePages) {
const compilerDom = require((0, uni_cli_shared_1.resolveBuiltIn)('@vue/compiler-dom'));
const { compile } = compilerDom;
compilerDom.compile = (template, options = {}) => {
if (options.filename) {
if (nvuePages[options.filename]) {
;
(options.bindingMetadata || (options.bindingMetadata = {})).__pageOptions = nvuePages[options.filename];
}
}
return compile(template, options);
};
}

View File

@@ -0,0 +1,2 @@
import { Plugin } from 'vite';
export declare function uniRenderjsPlugin(): Plugin;

View File

@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniRenderjsPlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function uniRenderjsPlugin() {
return {
name: 'uni:app-nvue-renderjs',
async transform(code, id) {
const { type } = (0, uni_cli_shared_1.parseRenderjs)(id);
if (!type) {
return;
}
return {
code: `export default {}`,
map: { mappings: '' },
};
},
};
}
exports.uniRenderjsPlugin = uniRenderjsPlugin;

View File

@@ -0,0 +1,8 @@
export declare function external(appService: boolean): string[];
export declare function globals(appService: boolean): {
[name: string]: string;
};
export declare function esbuildGlobals(appService: boolean): {
[name: string]: string;
};
export declare function isUTSComponent(tag: string): boolean;

View File

@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isUTSComponent = exports.esbuildGlobals = exports.globals = exports.external = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function external(appService) {
return appService ? ['vue'] : ['vue', 'vuex', 'pinia'];
}
exports.external = external;
function globals(appService) {
return appService
? { vue: 'Vue' }
: {
vue: 'Vue',
vuex: 'Vuex',
pinia: 'Pinia',
};
}
exports.globals = globals;
function esbuildGlobals(appService) {
return appService
? { vue: 'Vue' }
: {
vue: 'Vue',
vuex: 'uni.Vuex',
pinia: 'uni.Pinia',
};
}
exports.esbuildGlobals = esbuildGlobals;
function isUTSComponent(tag) {
const source = (0, uni_cli_shared_1.matchEasycom)(tag);
return !!(source && source.includes('uts-proxy'));
}
exports.isUTSComponent = isUTSComponent;

View File

@@ -0,0 +1,5 @@
import { ConfigEnv, UserConfig } from 'vite';
export declare function buildOptions({ appService, renderer, }: {
renderer: 'native' | undefined;
appService: boolean;
}, userConfig: UserConfig, _: ConfigEnv): UserConfig['build'];

View File

@@ -0,0 +1,74 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildOptions = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../utils");
function buildOptions({ appService, renderer, }, userConfig, _) {
const inputDir = process.env.UNI_INPUT_DIR;
const outputDir = process.env.UNI_OUTPUT_DIR;
// 开始编译时,清空输出目录
function emptyNVueDir() {
const nvueOutputDir = (0, utils_1.nvueOutDir)();
if (fs_1.default.existsSync(nvueOutputDir)) {
(0, uni_cli_shared_1.emptyDir)(nvueOutputDir);
}
}
function emptyOutDir() {
if (fs_1.default.existsSync(outputDir)) {
(0, uni_cli_shared_1.emptyDir)(outputDir);
}
}
if (renderer === 'native') {
if (appService) {
// 仅编译 main.js+App.vue 的时候才清空
emptyNVueDir();
emptyOutDir();
}
}
else {
if ((0, uni_cli_shared_1.isInHybridNVue)(userConfig)) {
emptyNVueDir();
}
else {
emptyOutDir();
}
}
const sourcemap = process.env.SOURCEMAP === 'true'
? 'hidden'
: userConfig.build?.sourcemap
? 'inline'
: false;
return {
// App 端目前仅提供 inline
sourcemap,
emptyOutDir: false,
assetsInlineLimit: 0,
rollupOptions: {
input: (0, uni_cli_shared_1.resolveMainPathOnce)(inputDir),
output: {
sourcemapPathTransform(relativeSourcePath, sourcemapPath) {
const sourcePath = (0, uni_cli_shared_1.normalizePath)(path_1.default.relative(inputDir, path_1.default.resolve(path_1.default.dirname(sourcemapPath), relativeSourcePath)));
if (sourcePath.startsWith('..')) {
return '';
}
return 'uni-app:///' + sourcePath;
},
manualChunks: {},
inlineDynamicImports: false,
chunkFileNames(chunk) {
if (chunk.isDynamicEntry && chunk.facadeModuleId) {
const filepath = path_1.default.relative(inputDir, chunk.facadeModuleId);
return (0, uni_cli_shared_1.normalizePath)(filepath.replace(path_1.default.extname(filepath), '.js'));
}
return '[name].js';
},
},
},
};
}
exports.buildOptions = buildOptions;

View File

@@ -0,0 +1,4 @@
import { Plugin, ResolvedConfig } from 'vite';
export declare function createConfigResolved({ createCssPostPlugin, }: {
createCssPostPlugin: (config: ResolvedConfig) => Plugin;
}): Plugin['configResolved'];

View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createConfigResolved = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function createConfigResolved({ createCssPostPlugin, }) {
return (config) => {
(0, uni_cli_shared_1.injectCssPlugin)(config);
(0, uni_cli_shared_1.injectCssPostPlugin)(config, createCssPostPlugin(config));
// 强制不inline
config.build.assetsInlineLimit = 0;
(0, uni_cli_shared_1.injectAssetPlugin)(config);
};
}
exports.createConfigResolved = createConfigResolved;

View File

@@ -0,0 +1,5 @@
import { UniVitePlugin } from '@dcloudio/uni-cli-shared';
export declare function uniAppPlugin({ renderer, appService, }?: {
renderer?: 'native';
appService: boolean;
}): UniVitePlugin;

View File

@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniAppPlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const uni_1 = require("./uni");
const build_1 = require("./build");
function uniAppPlugin({ renderer, appService, } = {
appService: false,
}) {
return {
name: 'uni:app',
uni: (0, uni_1.uniOptions)(),
config(config, env) {
return {
base: '/',
build: (0, build_1.buildOptions)({ renderer, appService }, config, env),
optimizeDeps: {
disabled: true,
},
resolve: {
alias: {
// vue-i18n 默认会启用 new Function 来构造翻译函数,导致在 Android 上可能报`TypeError: no access` 错误
// 故:启用 runtime 模式,内部定制了简易的 compileToFunction
'vue-i18n': (0, uni_cli_shared_1.resolveVueI18nRuntime)(),
},
},
};
},
};
}
exports.uniAppPlugin = uniAppPlugin;

View File

@@ -0,0 +1,2 @@
import { UniVitePlugin } from '@dcloudio/uni-cli-shared';
export declare function uniOptions(compilerType?: "vue" | "nvue"): UniVitePlugin['uni'];

View File

@@ -0,0 +1,67 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniOptions = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const uni_shared_1 = require("@dcloudio/uni-shared");
const uni_i18n_1 = require("@dcloudio/uni-i18n");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const nvue_1 = require("../../nvue");
const plugin_1 = require("../../nvue/plugin");
const utils_1 = require("../../nvue/utils");
const transformWxsProps_1 = require("./transforms/transformWxsProps");
function isAppNVueNativeTag(tag) {
return (0, utils_1.isUTSComponent)(tag) || (0, uni_shared_1.isAppNVueNativeTag)(tag);
}
function uniOptions(compilerType = process.env.UNI_COMPILER) {
const isNVueCompiler = compilerType === 'nvue';
return {
copyOptions() {
const platform = process.env.UNI_PLATFORM;
const inputDir = process.env.UNI_INPUT_DIR;
const outputDir = process.env.UNI_OUTPUT_DIR;
const targets = [];
// 自动化测试时,不启用隐私政策
if (!process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
targets.push({
src: 'androidPrivacy.json',
dest: outputDir,
transform(source) {
const options = (0, uni_cli_shared_1.initI18nOptions)(platform, inputDir, false, true);
if (!options) {
return;
}
return (0, uni_i18n_1.compileI18nJsonStr)(source.toString(), options);
},
});
const debugFilename = '__nvue_debug__';
if (fs_extra_1.default.existsSync(path_1.default.resolve(inputDir, debugFilename))) {
targets.push({
src: debugFilename,
dest: outputDir,
});
}
}
return {
assets: ['hybrid/html/**/*', 'uni_modules/*/hybrid/html/**/*'],
targets,
};
},
compilerOptions: {
isNativeTag: isNVueCompiler ? isAppNVueNativeTag : uni_shared_1.isAppNativeTag,
nodeTransforms: [
...(isNVueCompiler ? (0, nvue_1.initNVueNodeTransforms)() : [transformWxsProps_1.transformWxsProps]),
uni_cli_shared_1.transformTapToClick,
uni_cli_shared_1.transformMatchMedia,
uni_cli_shared_1.transformPageHead,
],
directiveTransforms: {
...(isNVueCompiler ? (0, plugin_1.initNVueDirectiveTransforms)() : {}),
},
},
};
}
exports.uniOptions = uniOptions;

View File

@@ -0,0 +1 @@
export declare const WXS_PROP: unique symbol;

View File

@@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WXS_PROP = void 0;
const compiler_core_1 = require("@vue/compiler-core");
exports.WXS_PROP = Symbol(`wxsProp`);
(0, compiler_core_1.registerRuntimeHelpers)({
[exports.WXS_PROP]: 'wp',
});

View File

@@ -0,0 +1,2 @@
import { NodeTransform } from '@vue/compiler-core';
export declare const transformWxsProps: NodeTransform;

View File

@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformWxsProps = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const uni_shared_1 = require("@dcloudio/uni-shared");
const compiler_core_1 = require("@vue/compiler-core");
const runtimeHelpers_1 = require("./runtimeHelpers");
const transformWxsProps = (node, context) => {
if (!(0, uni_cli_shared_1.isElementNode)(node)) {
return;
}
node.props.forEach((prop) => {
if ((0, uni_cli_shared_1.isDirectiveNode)(prop) && prop.arg && (0, uni_cli_shared_1.isSimpleExpressionNode)(prop.arg)) {
const { content } = prop.arg;
if (content.startsWith(uni_shared_1.ATTR_CHANGE_PREFIX)) {
const propName = content.substring(uni_shared_1.ATTR_CHANGE_PREFIX.length);
const wxsProp = (0, compiler_core_1.findProp)(node, propName, true);
if (wxsProp && (0, uni_cli_shared_1.isDirectiveNode)(wxsProp) && wxsProp.exp) {
wxsProp.exp = (0, compiler_core_1.createCompoundExpression)([
context.helperString(runtimeHelpers_1.WXS_PROP),
'(',
wxsProp.exp,
')',
]);
}
}
}
});
};
exports.transformWxsProps = transformWxsProps;

View File

@@ -0,0 +1,8 @@
import { Plugin } from 'vite';
import { FilterPattern } from '@rollup/pluginutils';
interface UniEasycomPluginOptions {
include?: FilterPattern;
exclude?: FilterPattern;
}
export declare function uniEasycomPlugin(options: UniEasycomPluginOptions): Plugin;
export {};

View File

@@ -0,0 +1,50 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniEasycomPlugin = void 0;
const path_1 = __importDefault(require("path"));
const shared_1 = require("@vue/shared");
const pluginutils_1 = require("@rollup/pluginutils");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function uniEasycomPlugin(options) {
const filter = (0, pluginutils_1.createFilter)(options.include, options.exclude);
return {
name: 'uni:app-easycom',
transform(code, id) {
if (!filter(id)) {
return;
}
const { filename } = (0, uni_cli_shared_1.parseVueRequest)(id);
if (!uni_cli_shared_1.EXTNAME_VUE_TEMPLATE.includes(path_1.default.extname(filename))) {
return;
}
if (!code.includes('_resolveComponent')) {
return;
}
let i = 0;
const importDeclarations = [];
code = code.replace(/_resolveComponent\("(.+?)"(, true)?\)/g, (str, name) => {
if (name && !name.startsWith('_')) {
const source = (0, uni_cli_shared_1.matchEasycom)(name);
if (source) {
// 处理easycom组件优先级
return (0, uni_cli_shared_1.genResolveEasycomCode)(importDeclarations, str, (0, uni_cli_shared_1.addImportDeclaration)(importDeclarations, `__easycom_${i++}`, source, source.includes('uts-proxy')
? (0, shared_1.capitalize)((0, shared_1.camelize)(name)) + 'Component'
: ''));
}
}
return str;
});
if (importDeclarations.length) {
code = importDeclarations.join('') + code;
}
return {
code,
map: null,
};
},
};
}
exports.uniEasycomPlugin = uniEasycomPlugin;

View File

@@ -0,0 +1,2 @@
import { Plugin } from 'vite';
export declare function uniManifestJsonPlugin(): Plugin;

View File

@@ -0,0 +1,43 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniManifestJsonPlugin = void 0;
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function uniManifestJsonPlugin() {
return (0, uni_cli_shared_1.defineUniManifestJsonPlugin)((opts) => {
const inputDir = process.env.UNI_INPUT_DIR;
return {
name: 'uni:app-manifest-json',
enforce: 'pre',
transform(code, id) {
if (!opts.filter(id)) {
return;
}
this.addWatchFile(path_1.default.resolve(inputDir, 'manifest.json'));
(0, uni_cli_shared_1.getLocaleFiles)(path_1.default.resolve(inputDir, 'locale')).forEach((filepath) => {
this.addWatchFile(filepath);
});
const manifestJson = (0, uni_cli_shared_1.normalizeAppManifestJson)((0, uni_cli_shared_1.parseJson)(code), (0, uni_cli_shared_1.parsePagesJsonOnce)(inputDir, process.env.UNI_PLATFORM));
// 生成一个空的 app-config.js兼容基座已有规范
this.emitFile({
fileName: uni_cli_shared_1.APP_CONFIG,
type: 'asset',
source: '(function(){})();',
});
this.emitFile({
fileName: `manifest.json`,
type: 'asset',
source: JSON.stringify(manifestJson, null, 2),
});
return {
code: '',
map: null,
};
},
};
});
}
exports.uniManifestJsonPlugin = uniManifestJsonPlugin;

View File

@@ -0,0 +1,2 @@
import { Plugin } from 'vite';
export declare function uniStatsPlugin(): Plugin;

View File

@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniStatsPlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const emittedHashMap = new WeakMap();
function uniStatsPlugin() {
let resolvedConfig;
return {
name: 'uni:app-stats',
enforce: 'post',
configResolved(config) {
resolvedConfig = config;
emittedHashMap.set(resolvedConfig, new Map());
},
writeBundle(_, bundle) {
if (resolvedConfig.isProduction) {
// 仅dev生效
return;
}
const emittedHash = emittedHashMap.get(resolvedConfig);
const changedFiles = [];
Object.keys(bundle).forEach((filename) => {
const outputFile = bundle[filename];
let outputFileHash = '';
if (outputFile.type === 'asset') {
outputFileHash = (0, uni_cli_shared_1.hash)(outputFile.source);
}
else {
outputFileHash = (0, uni_cli_shared_1.hash)(outputFile.code);
}
if (emittedHash.get(filename) !== outputFileHash) {
emittedHash.set(filename, outputFileHash);
changedFiles.push(filename);
}
});
process.env.UNI_APP_CHANGED_FILES = changedFiles.length
? JSON.stringify(changedFiles)
: '';
},
};
}
exports.uniStatsPlugin = uniStatsPlugin;

View File

@@ -0,0 +1,4 @@
import { Plugin } from 'vite';
export declare function uniTemplatePlugin({ renderer, }?: {
renderer?: 'native';
}): Plugin;

View File

@@ -0,0 +1,38 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniTemplatePlugin = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const utils_1 = require("../utils");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function uniTemplatePlugin({ renderer, } = {}) {
let outputDir;
return {
name: 'uni:app-template',
enforce: 'post',
configResolved() {
outputDir = process.env.UNI_OUTPUT_DIR;
if (renderer !== 'native') {
fs_extra_1.default.copySync((0, uni_cli_shared_1.resolveBuiltIn)('@dcloudio/uni-app-plus/dist/uni-app-view.umd.js'), path_1.default.resolve(outputDir, 'uni-app-view.umd.js'), {
overwrite: true,
});
}
fs_extra_1.default.copySync(utils_1.templateDir, outputDir, {
overwrite: true,
filter(src) {
if (renderer === 'native') {
if (src.includes('__uniappquill') ||
src.includes('__uniappautomator')) {
return false;
}
}
return !src.includes('__uniappview.html');
},
});
},
};
}
exports.uniTemplatePlugin = uniTemplatePlugin;

View File

@@ -0,0 +1,2 @@
export declare const templateDir: string;
export declare function nvueOutDir(): string;

View File

@@ -0,0 +1,12 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.nvueOutDir = exports.templateDir = void 0;
const path_1 = __importDefault(require("path"));
exports.templateDir = path_1.default.resolve(__dirname, '../lib/template/');
function nvueOutDir() {
return path_1.default.join(process.env.UNI_OUTPUT_DIR, '../.nvue');
}
exports.nvueOutDir = nvueOutDir;

View File

@@ -0,0 +1 @@
export declare function initVuePlugins(): import("vite").Plugin[];

View File

@@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initVuePlugins = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const template_1 = require("../plugins/template");
const manifestJson_1 = require("../plugins/manifestJson");
const stats_1 = require("../plugins/stats");
const easycom_1 = require("../plugins/easycom");
const confusion_1 = require("./plugins/confusion");
const mainJs_1 = require("./plugins/mainJs");
const pagesJson_1 = require("./plugins/pagesJson");
const renderjs_1 = require("./plugins/renderjs");
const plugin_1 = require("./plugin");
function initUniCssScopedPluginFilter(inputDir) {
const styleIsolation = (0, uni_cli_shared_1.getAppStyleIsolation)((0, uni_cli_shared_1.parseManifestJsonOnce)(inputDir));
if (styleIsolation === 'shared') {
return;
}
if (styleIsolation === 'isolated') {
// isolated: 对所有非 App.vue 增加 scoped
return (id) => (0, uni_cli_shared_1.isVueSfcFile)(id) && !(0, uni_cli_shared_1.isAppVue)(id);
}
// apply-shared: 仅对非页面组件增加 scoped
return (id) => (0, uni_cli_shared_1.isVueSfcFile)(id) && !(0, uni_cli_shared_1.isAppVue)(id) && !(0, uni_cli_shared_1.isUniPageFile)(id, inputDir);
}
function initVuePlugins() {
const plugins = [
(0, easycom_1.uniEasycomPlugin)({ exclude: uni_cli_shared_1.UNI_EASYCOM_EXCLUDE }),
(0, uni_cli_shared_1.uniHBuilderXConsolePlugin)(),
(0, mainJs_1.uniMainJsPlugin)(),
(0, manifestJson_1.uniManifestJsonPlugin)(),
(0, pagesJson_1.uniPagesJsonPlugin)(),
(0, uni_cli_shared_1.uniViteInjectPlugin)('uni:app-inject', (0, uni_cli_shared_1.initAppProvide)()),
(0, renderjs_1.uniRenderjsPlugin)(),
(0, template_1.uniTemplatePlugin)(),
(0, stats_1.uniStatsPlugin)(),
(0, plugin_1.uniAppVuePlugin)(),
(0, confusion_1.uniConfusionPlugin)(),
];
const filter = initUniCssScopedPluginFilter(process.env.UNI_INPUT_DIR);
if (filter) {
plugins.unshift((0, uni_cli_shared_1.uniCssScopedPlugin)({ filter }));
}
return plugins;
}
exports.initVuePlugins = initVuePlugins;

View File

@@ -0,0 +1,2 @@
import { UniVitePlugin } from '@dcloudio/uni-cli-shared';
export declare function uniAppVuePlugin(): UniVitePlugin;

View File

@@ -0,0 +1,112 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniAppVuePlugin = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const renderjs_1 = require("../plugins/renderjs");
const configResolved_1 = require("../../plugin/configResolved");
const utils_1 = require("../../utils");
const code_1 = require("@dcloudio/uni-cli-shared/dist/json/app/pages/code");
function uniAppVuePlugin() {
const inputDir = process.env.UNI_INPUT_DIR;
const mainPath = (0, uni_cli_shared_1.resolveMainPathOnce)(inputDir);
let appCss = '';
function normalizeCssChunkFilename(id) {
return (0, uni_cli_shared_1.removeExt)((0, uni_cli_shared_1.normalizePath)(path_1.default.relative(inputDir, id))) + '.css';
}
return {
name: 'uni:app-vue',
config() {
return {
css: {
postcss: {
plugins: (0, uni_cli_shared_1.initPostcssPlugin)({
uniApp: (0, uni_cli_shared_1.parseRpx2UnitOnce)(inputDir, process.env.UNI_PLATFORM),
}),
},
},
build: {
rollupOptions: {
external: ['vue', '@vue/shared'],
output: {
name: 'AppService',
banner: uni_cli_shared_1.polyfillCode + code_1.restoreGlobalCode,
format: process.env.UNI_APP_CODE_SPLITING ? 'amd' : 'iife',
amd: {
autoId: true,
},
entryFileNames: uni_cli_shared_1.APP_SERVICE_FILENAME,
globals: {
vue: 'Vue',
'@vue/shared': 'uni.VueShared',
},
},
},
},
};
},
configResolved: (0, configResolved_1.createConfigResolved)({
createCssPostPlugin(config) {
return (0, uni_cli_shared_1.cssPostPlugin)(config, {
platform: 'app',
chunkCssFilename(id) {
if (id === mainPath) {
return 'app.css';
}
else if ((0, uni_cli_shared_1.isUniPageSfcFile)(id, inputDir)) {
return normalizeCssChunkFilename(id);
}
},
chunkCssCode(filename, cssCode) {
if (filename === 'app.css') {
if (!appCss) {
appCss = fs_extra_1.default.readFileSync((0, uni_cli_shared_1.resolveBuiltIn)('@dcloudio/uni-app-plus/dist/style.css'), 'utf8');
}
return appCss + '\n' + cssCode;
}
return cssCode;
},
});
},
}),
generateBundle(_, bundle) {
this.emitFile({
fileName: '__uniappview.html',
source: genViewHtml(bundle),
type: 'asset',
});
},
};
}
exports.uniAppVuePlugin = uniAppVuePlugin;
function genViewHtml(bundle) {
const viewHtmlStr = fs_extra_1.default.readFileSync(path_1.default.join(utils_1.templateDir, '__uniappview.html'), 'utf8');
const { globalStyle } = (0, uni_cli_shared_1.parsePagesJsonOnce)(process.env.UNI_INPUT_DIR, process.env.UNI_PLATFORM);
const { darkmode = false } = (0, uni_cli_shared_1.getPlatformManifestJsonOnce)();
const __uniConfig = {
globalStyle: {
rpxCalcMaxDeviceWidth: globalStyle.rpxCalcMaxDeviceWidth,
rpxCalcBaseDeviceWidth: globalStyle.rpxCalcBaseDeviceWidth,
},
darkmode,
};
const wxsCode = bundle[renderjs_1.APP_WXS_JS]
? `<script src="${renderjs_1.APP_WXS_JS}"></script>`
: '';
const renderjsCode = bundle[renderjs_1.APP_RENDERJS_JS]
? `<script src="${renderjs_1.APP_RENDERJS_JS}"></script>`
: '';
const automatorCode = process.env.UNI_AUTOMATOR_WS_ENDPOINT
? `<script src="__uniappautomator.js"></script>`
: '';
return viewHtmlStr
.toString()
.replace('<!--wxsCode-->', wxsCode)
.replace('<!--renderjsCode-->', renderjsCode)
.replace('<!--automatorCode-->', automatorCode)
.replace('/*__uniConfig*/', `var __uniConfig = ${JSON.stringify(__uniConfig)}`);
}

View File

@@ -0,0 +1,2 @@
import { Plugin } from 'vite';
export declare function uniConfusionPlugin(): Plugin;

View File

@@ -0,0 +1,65 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniConfusionPlugin = void 0;
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function uniConfusionPlugin() {
const inputDir = process.env.UNI_INPUT_DIR;
const hasConfusion = process.env.NODE_ENV === 'production' && (0, uni_cli_shared_1.hasConfusionFile)(inputDir);
return {
name: 'uni:app-vue-confusion',
enforce: 'post',
apply: 'build',
config() {
if (!hasConfusion) {
return;
}
return {
build: {
rollupOptions: {
output: {
format: process.env.UNI_APP_CODE_SPLITING ? 'amd' : 'cjs',
manualChunks(id) {
if ((0, uni_cli_shared_1.isConfusionFile)(path_1.default.relative(inputDir, id))) {
return (0, uni_cli_shared_1.removeExt)(uni_cli_shared_1.APP_CONFUSION_FILENAME);
}
},
},
},
},
};
},
generateBundle(_, bundle) {
if (!hasConfusion) {
return;
}
const appConfusionChunk = bundle[uni_cli_shared_1.APP_CONFUSION_FILENAME];
if (!appConfusionChunk) {
return;
}
appConfusionChunk.code = wrapperAppConfusionCode(appConfusionChunk.code);
const appServiceChunk = bundle[uni_cli_shared_1.APP_SERVICE_FILENAME];
if (!appServiceChunk) {
return;
}
appServiceChunk.code = wrapperAppServiceCode(appServiceChunk.code);
},
};
}
exports.uniConfusionPlugin = uniConfusionPlugin;
function replaceRequireVueCode(code) {
return code.replace(/require\(['"]vue['"]\)/gi, `$cjs_require$('vue')`);
}
function replaceRequireAppConfusionCode(code) {
return code.replace(new RegExp(`require\\(['"].\\/${uni_cli_shared_1.APP_CONFUSION_FILENAME}['"]\\)`, 'gi'), `$cjs_require$('./${uni_cli_shared_1.APP_CONFUSION_FILENAME}')`);
}
function wrapperAppServiceCode(code) {
return replaceRequireAppConfusionCode(replaceRequireVueCode(code));
}
function wrapperAppConfusionCode(code) {
return `function $cjs_require$(name){if(name==='vue'){return Vue;}if(name==='./${uni_cli_shared_1.APP_CONFUSION_FILENAME}'){return $appConfusion$;}};const $appConfusion$ = {};(function(exports){${replaceRequireVueCode(code)}})($appConfusion$);
`;
}

View File

@@ -0,0 +1 @@
export declare function uniMainJsPlugin(): import("vite").Plugin;

View File

@@ -0,0 +1,30 @@
"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 (0, uni_cli_shared_1.defineUniMainJsPlugin)((opts) => {
return {
name: 'uni:app-vue-main-js',
enforce: 'pre',
transform(code, id) {
if (opts.filter(id)) {
code = code.includes('createSSRApp')
? createApp(code)
: createLegacyApp(code);
return {
code: `import './${uni_cli_shared_1.PAGES_JSON_JS}';` + code,
map: { mappings: '' },
};
}
},
};
});
}
exports.uniMainJsPlugin = uniMainJsPlugin;
function createApp(code) {
return `${code.replace('createSSRApp', 'createVueApp as createSSRApp')};const {app:__app__,Vuex:__Vuex__,Pinia:__Pinia__}=createApp();uni.Vuex=__Vuex__;uni.Pinia=__Pinia__;__app__.provide('__globalStyles', __uniConfig.styles);__app__._component.mpType='app';__app__._component.render=()=>{};__app__.mount("#app");`;
}
function createLegacyApp(code) {
return `function createApp(rootComponent,rootProps){rootComponent.mpTye='app';rootComponent.render=()=>{};const app=createVueApp(rootComponent,rootProps);app.provide('__globalStyles', __uniConfig.styles);const oldMount=app.mount;app.mount=(container)=>{const appVm=oldMount.call(app,container);return appVm;};return app;};${code.replace('createApp', 'createVueApp')}`;
}

View File

@@ -0,0 +1,2 @@
import { Plugin } from 'vite';
export declare function uniPagesJsonPlugin(): Plugin;

View File

@@ -0,0 +1,51 @@
"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 path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const esbuild_1 = require("../../nvue/plugins/esbuild");
function uniPagesJsonPlugin() {
return (0, uni_cli_shared_1.defineUniPagesJsonPlugin)((opts) => {
return {
name: 'uni:app-vue-pages-json',
enforce: 'pre',
transform(code, id) {
if (!opts.filter(id)) {
return;
}
this.addWatchFile(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'pages.json'));
(0, uni_cli_shared_1.getLocaleFiles)(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'locale')).forEach((filepath) => {
this.addWatchFile(filepath);
});
const pagesJson = (0, uni_cli_shared_1.normalizePagesJson)(code, process.env.UNI_PLATFORM);
pagesJson.pages.forEach((page) => {
if (!page.style.isNVue) {
this.addWatchFile(path_1.default.resolve(process.env.UNI_INPUT_DIR, page.path + '.vue'));
}
});
this.emitFile({
fileName: uni_cli_shared_1.APP_CONFIG_SERVICE,
type: 'asset',
source: (0, uni_cli_shared_1.normalizeAppConfigService)(pagesJson, (0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR)),
});
return {
code: `import './${uni_cli_shared_1.MANIFEST_JSON_JS}'\n` +
(0, uni_cli_shared_1.normalizeAppPagesJson)(pagesJson),
map: { mappings: '' },
};
},
generateBundle(_, bundle) {
const outputFile = bundle[uni_cli_shared_1.APP_CONFIG_SERVICE];
if (outputFile && outputFile.type === 'asset') {
// 补充 nvue styles
;
outputFile.source = (0, esbuild_1.wrapperNVueAppStyles)(outputFile.source);
}
},
};
});
}
exports.uniPagesJsonPlugin = uniPagesJsonPlugin;

View File

@@ -0,0 +1,4 @@
import { Plugin } from 'vite';
export declare const APP_WXS_JS = "app-wxs.js";
export declare const APP_RENDERJS_JS = "app-renderjs.js";
export declare function uniRenderjsPlugin(): Plugin;

View File

@@ -0,0 +1,122 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniRenderjsPlugin = exports.APP_RENDERJS_JS = exports.APP_WXS_JS = void 0;
const path_1 = __importDefault(require("path"));
const debug_1 = __importDefault(require("debug"));
const uni_shared_1 = require("@dcloudio/uni-shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const debugRenderjs = (0, debug_1.default)('uni:app-renderjs');
exports.APP_WXS_JS = 'app-wxs.js';
exports.APP_RENDERJS_JS = 'app-renderjs.js';
const wxsModulesCache = new WeakMap();
const renderjsModulesCache = new WeakMap();
function uniRenderjsPlugin() {
let resolvedConfig;
let changed = false;
return {
name: 'uni:app-vue-renderjs',
configResolved(config) {
resolvedConfig = config;
wxsModulesCache.set(resolvedConfig, new Map());
renderjsModulesCache.set(resolvedConfig, new Map());
},
async transform(code, id) {
const { type, name, filename } = (0, uni_cli_shared_1.parseRenderjs)(id);
if (!type) {
return;
}
if (type !== 'wxs' && type !== 'renderjs') {
return;
}
debugRenderjs(id);
this.addWatchFile((0, uni_cli_shared_1.cleanUrl)(id));
if (!name) {
this.error((0, uni_cli_shared_1.missingModuleName)(type, code));
}
const modulePath = (0, uni_cli_shared_1.normalizePath)(path_1.default.normalize(path_1.default.relative(process.env.UNI_INPUT_DIR, id)));
const moduleHashId = (0, uni_cli_shared_1.hash)(modulePath);
const globalName = type === 'wxs' ? uni_shared_1.WXS_MODULES : uni_shared_1.RENDERJS_MODULES;
const { isProduction } = resolvedConfig;
const resultCode = normalizeCode(type === 'wxs'
? await transformWxs(code, filename, `__${globalName}['${moduleHashId}']`, isProduction)
: await transformRenderjs(code, filename, `__${globalName}['${moduleHashId}']`, isProduction), globalName, isProduction);
if (type === 'wxs') {
wxsModulesCache.get(resolvedConfig).set(moduleHashId, resultCode);
}
else {
renderjsModulesCache.get(resolvedConfig).set(moduleHashId, resultCode);
}
changed = true;
debugRenderjs(type, modulePath, moduleHashId);
return {
code: `export default Comp => {
;(Comp.$${type} || (Comp.$${type} = [])).push('${name}')
;(Comp.$${globalName} || (Comp.$${globalName} = {}))['${name}'] = '${moduleHashId}'
}`,
map: { mappings: '' },
};
},
generateBundle() {
if (!changed) {
return;
}
const wxsCode = [...wxsModulesCache.get(resolvedConfig).values()].join('\n');
if (wxsCode) {
this.emitFile({
fileName: exports.APP_WXS_JS,
source: `var __${uni_shared_1.WXS_MODULES}={};\n` + wxsCode,
type: 'asset',
});
}
const renderjsCode = [
...renderjsModulesCache.get(resolvedConfig).values(),
].join('\n');
if (renderjsCode) {
this.emitFile({
fileName: exports.APP_RENDERJS_JS,
source: `var __${uni_shared_1.RENDERJS_MODULES}={};\n` + renderjsCode,
type: 'asset',
});
}
},
};
}
exports.uniRenderjsPlugin = uniRenderjsPlugin;
function normalizeCode(code, globalName, isProduction) {
return code.replace(isProduction
? `var __${globalName}=__${globalName}||{};`
: `var __${globalName} = __${globalName} || {};`, '');
}
function transformWxs(code, filename, globalName, isProduction) {
return (0, uni_cli_shared_1.transformWithEsbuild)(code, filename, {
format: 'iife',
globalName,
target: 'es6',
minify: isProduction ? true : false,
bundle: true,
write: false,
}).then((res) => {
if (res.outputFiles) {
return res.outputFiles[0].text;
}
return '';
});
}
function transformRenderjs(code, filename, globalName, isProduction) {
return (0, uni_cli_shared_1.transformWithEsbuild)(code, filename, {
format: 'iife',
globalName,
target: 'es6',
minify: isProduction ? true : false,
bundle: true,
write: false,
}).then((res) => {
if (res.outputFiles) {
return res.outputFiles[0].text;
}
return '';
});
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

View File

@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>View</title>
<link rel="stylesheet" href="app.css" />
<script>/*__uniConfig*/</script>
<script>
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
CSS.supports('top: constant(a)'))
document.write(
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
(coverSupport ? ', viewport-fit=cover' : '') + '" />')
</script>
</head>
<body>
<div id="app"></div>
<script src="uni-app-view.umd.js"></script>
<!--wxsCode-->
<!--renderjsCode-->
<!--automatorCode-->
</body>
</html>

View File

@@ -0,0 +1,44 @@
{
"name": "@dcloudio/uni-app-vite",
"version": "3.0.0-3090520231028001",
"description": "uni-app-vite",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist",
"lib"
],
"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"
},
"license": "Apache-2.0",
"gitHead": "33e807d66e1fe47e2ee08ad9c59247e37b8884da",
"dependencies": {
"@dcloudio/uni-cli-shared": "3.0.0-3090520231028001",
"@dcloudio/uni-i18n": "3.0.0-3090520231028001",
"@dcloudio/uni-nvue-styler": "3.0.0-3090520231028001",
"@dcloudio/uni-shared": "3.0.0-3090520231028001",
"@rollup/pluginutils": "^4.2.0",
"@vitejs/plugin-vue": "^4.2.1",
"@vue/compiler-dom": "3.2.47",
"@vue/compiler-sfc": "3.2.47",
"debug": "^4.3.3",
"fs-extra": "^10.0.0",
"picocolors": "^1.0.0"
},
"devDependencies": {
"@types/debug": "^4.1.7",
"@types/fs-extra": "^9.0.13",
"@vue/compiler-core": "3.2.47",
"esbuild": "^0.17.5",
"postcss": "^8.4.21",
"rollup": "^3.7.0",
"vite": "^4.0.0",
"vue": "3.2.47"
}
}