前端 uni-app 重写: 9页面 H5

This commit is contained in:
zhiqui
2026-11-15 15:09:37 +08:00
parent 513b53672e
commit ea7c2529e9
24104 changed files with 3667749 additions and 0 deletions
+202
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.
+2
View File
@@ -0,0 +1,2 @@
declare const _default: () => (import("vite").Plugin<any> | import("rollup").Plugin<any>[])[];
export default _default;
+152
View File
@@ -0,0 +1,152 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const plugin_basic_ssl_1 = __importDefault(require("@vitejs/plugin-basic-ssl"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const vueCompilerDom = __importStar(require("@vue/compiler-dom"));
const uniCliShared = __importStar(require("@dcloudio/uni-cli-shared"));
const plugin_1 = require("./plugin");
const config_1 = require("./plugin/config");
const css_1 = require("./plugins/css");
const easycom_1 = require("./plugins/easycom");
const inject_1 = require("./plugins/inject");
const mainJs_1 = require("./plugins/mainJs");
const manifestJson_1 = require("./plugins/manifestJson");
const pagesJson_1 = require("./plugins/pagesJson");
const postVue_1 = require("./plugins/postVue");
const renderjs_1 = require("./plugins/renderjs");
const resolveId_1 = require("./plugins/resolveId");
const setup_1 = require("./plugins/setup");
const ssr_1 = require("./plugins/ssr");
const sourcemap_1 = require("./plugins/sourcemap");
const customElement_1 = require("./plugins/customElement");
const api_1 = require("./plugins/api");
const mouseToTouch_1 = require("./plugins/mouseToTouch");
const polyfill_1 = require("./utils/polyfill");
if (process.env.UNI_APP_STYLE_ISOLATION_VERSION === '2' &&
process.env.UNI_APP_X === 'true') {
(0, polyfill_1.rewriteCompilerSfcParse)();
}
exports.default = () => {
const isNewStyleIsolation = process.env.UNI_APP_STYLE_ISOLATION_VERSION === '2';
const uasm = process.env.UNI_APP_X === 'true' ? (0, uni_cli_shared_1.initUasmWebTransformOptions)() : undefined;
// 从 manifest.json 的 h5.devServer 中解析 HTTPS 扩展配置,按需注入 basic-ssl 插件。
const h5BasicSslPlugin = resolveH5BasicSslPlugin();
return [
...(process.env.UNI_APP_X === 'true' && (0, uni_cli_shared_1.isNormalCompileTarget)()
? [(0, uni_cli_shared_1.uniWorkersPlugin)(), (0, uni_cli_shared_1.uniJavaScriptWorkersPlugin)()]
: []),
...((0, uni_cli_shared_1.isEnableConsole)() ? [(0, uni_cli_shared_1.uniHBuilderXConsolePlugin)('uni.__f__')] : []),
...(process.env.UNI_APP_X === 'true'
? [
(0, uni_cli_shared_1.uniDecryptUniModulesPlugin)(),
(0, uni_cli_shared_1.uniUasmPlugin)(),
(0, uni_cli_shared_1.uniUTSUVueJavaScriptPlugin)(),
// H5 的标准 JS/TS 不走 uts2js,脚本宏和 UASM 必须在标准 plugin-vue 前完成转换。
(0, uni_cli_shared_1.uniAppXStandardScriptPlugin)({
uasm,
workers: {
...(0, uni_cli_shared_1.initWorkerTransformOptions)(),
rewriteRootDir: undefined,
},
}),
...((0, uni_cli_shared_1.isUniAppXWebVapor)() ? [(0, uni_cli_shared_1.uniWebVaporElementPlugin)()] : []),
(0, uni_cli_shared_1.resolveUTSCompiler)().uts2js({
platform: 'web',
dom2: (0, uni_cli_shared_1.isUniAppXWebVapor)(),
excludeStandardTypeScript: true,
inputDir: process.env.UNI_INPUT_DIR,
version: process.env.UNI_COMPILER_VERSION,
sourceMap: (0, uni_cli_shared_1.enableSourceMap)(),
cacheRoot: path_1.default.resolve(process.env.UNI_APP_X_CACHE_DIR, '.uts2js/cache'),
modules: {
vueCompilerDom,
uniCliShared,
},
scriptMacros: {
createUniAppXScriptMacrosTransformer: uniCliShared.createUniAppXScriptMacrosTransformer,
},
extApi: (0, uni_cli_shared_1.initUts2jsExtApiOptions)(),
uasm,
workers: {
extname: '.js',
createWorkerTransformer: uniCliShared.createWorkerTransformer,
resolve: () => {
return (0, uni_cli_shared_1.getWorkers)();
},
},
}),
]
: []),
(0, easycom_1.uniEasycomPlugin)({ exclude: uni_cli_shared_1.UNI_EASYCOM_EXCLUDE }),
(0, uni_cli_shared_1.uniCssScopedPlugin)({
filter: (id) => {
// Vapor 模式下,App.vue 也需要处理
if (isNewStyleIsolation) {
return (0, uni_cli_shared_1.isVueSfcFile)(id);
}
return (0, uni_cli_shared_1.isVueSfcFile)(id) && !(0, uni_cli_shared_1.isAppVue)(id);
},
}),
(0, resolveId_1.uniResolveIdPlugin)(),
...(process.env.UNI_COMPILE_TARGET === 'uni_modules'
? []
: [(0, mainJs_1.uniMainJsPlugin)(), (0, manifestJson_1.uniManifestJsonPlugin)(), (0, pagesJson_1.uniPagesJsonPlugin)()]),
(0, inject_1.uniInjectPlugin)(),
(0, css_1.uniCssPlugin)(),
(0, ssr_1.uniSSRPlugin)(),
(0, setup_1.uniSetupPlugin)(),
(0, renderjs_1.uniRenderjsPlugin)(),
...(h5BasicSslPlugin ? [h5BasicSslPlugin] : []),
(0, plugin_1.uniH5Plugin)(),
(0, mouseToTouch_1.uniMouseToTouchPlugin)(),
...(process.env.UNI_COMPILE_TARGET === 'uni_modules'
? [(0, uni_cli_shared_1.uniEncryptUniModulesAssetsPlugin)(), (0, uni_cli_shared_1.uniEncryptUniModulesPlugin)()]
: []),
(0, postVue_1.uniPostVuePlugin)(),
(0, sourcemap_1.uniPostSourceMapPlugin)(),
(0, customElement_1.uniCustomElementPlugin)(),
(0, api_1.uniApiPlugin)(),
];
};
function resolveH5BasicSslPlugin() {
const inputDir = process.env.UNI_INPUT_DIR;
if (!inputDir) {
return;
}
// 这里只关心是否启用自动证书,以及透传给 basic-ssl 的那部分参数。
const { enableBasicSsl, basicSslOptions } = (0, config_1.resolveManifestServerOptions)(inputDir);
if (!enableBasicSsl) {
return;
}
// 需要在真正的 Vite 插件数组中注册,才能参与 configResolved 并注入证书。
return Object.assign((0, plugin_basic_ssl_1.default)(basicSslOptions), {
apply: 'serve',
});
}
@@ -0,0 +1,19 @@
import type { Plugin, ResolvedConfig, ServerOptions } from 'vite';
export interface ManifestBasicSslOptions {
name?: string;
domains?: string[];
certDir?: string;
}
type ManifestServerOptions = ServerOptions & {
https?: ServerOptions['https'] | true;
basicSsl?: ManifestBasicSslOptions;
};
export declare function createConfig(options: {
resolvedConfig: ResolvedConfig | null;
}): Plugin['config'];
export declare function resolveManifestServerOptions(inputDir: string): {
server: ManifestServerOptions;
basicSslOptions: ManifestBasicSslOptions | undefined;
enableBasicSsl: boolean;
};
export {};
+188
View File
@@ -0,0 +1,188 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveManifestServerOptions = exports.createConfig = void 0;
const os_1 = __importDefault(require("os"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const shared_1 = require("@vue/shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../utils");
const esbuildPrePlugin_1 = require("./esbuild/esbuildPrePlugin");
const ssr_1 = require("./configureServer/ssr");
function createConfig(options) {
return function config(config, env) {
const inputDir = process.env.UNI_INPUT_DIR;
if ((0, uni_cli_shared_1.isInHBuilderX)()) {
if (!fs_1.default.existsSync(path_1.default.resolve(inputDir, 'index.html'))) {
console.error(`请确认您的项目模板是否支持vue3:根目录缺少 index.html`);
process.exit();
}
}
// 先对 manifest 中的 devServer 做一次清洗,避免把自定义字段直接透传给 Vite。
const { server: manifestServer } = resolveManifestServerOptions(inputDir);
const server = {
hmr: process.env.UNI_AUTOMATOR_WS_ENDPOINT
? false
: {
// mac 内置浏览器版本较低不支持 globalThis,而 overlay 使用了 globalThis
overlay: os_1.default.platform() !== 'win32'
? process.env.UNI_H5_BROWSER !== 'builtin'
: true,
},
fs: { strict: false },
watch: {
ignored: [
'**/uniCloud-aliyun/**',
'**/uniCloud-tcb/**',
'**/uniCloud-alipay/**',
'**/uniCloud-dcloud/**',
'**/uni_modules/uniCloud/**',
'**/__snapshots__/**',
(0, uni_cli_shared_1.normalizePath)(path_1.default.join(inputDir, 'unpackage/**')),
(0, uni_cli_shared_1.normalizePath)(path_1.default.join(inputDir, 'dist/**')),
],
},
...manifestServer,
};
if ((0, uni_cli_shared_1.runByHBuilderX)()) {
// 仅在 HBuilderX 中运行时,将 host 设置为 true,cli 项目命令行运行需要自行开启 --host 参数
server.host = true;
}
if (server.port === '') {
delete server.port;
}
const { server: userServer } = config;
if (userServer) {
if ((0, shared_1.hasOwn)(userServer, 'host')) {
server.host = userServer.host;
}
if ((0, shared_1.hasOwn)(userServer, 'fs')) {
(0, shared_1.extend)(server.fs, userServer.fs);
}
if ((0, shared_1.hasOwn)(userServer, 'watch')) {
(0, shared_1.extend)(server.watch, userServer.watch);
}
}
let sourcemapPathTransform = undefined;
const ssr = (0, uni_cli_shared_1.isSsr)(env.command, config);
const bundleWebVaporSsr = ssr && env.command === 'build' && (0, uni_cli_shared_1.isUniAppXWebVapor)();
const ssrExternal = ssr
? bundleWebVaporSsr
? (0, ssr_1.getWebVaporSsrExternalModules)()
: (0, ssr_1.getSsrExternalModules)()
: ssr_1.external;
if (
// 仅在 uni-app-x 模式下,且非开发模式,且需要 sourcemap 时,才进行 sourcemap 路径转换
process.env.UNI_APP_X === 'true' &&
process.env.NODE_ENV !== 'development' &&
(0, uni_cli_shared_1.withSourcemap)(config)) {
sourcemapPathTransform = transformSourcemapPath;
}
return {
legacy: {
// 目前先使用旧模式
proxySsrExternalModules: true,
},
css: {
postcss: {
plugins: (0, uni_cli_shared_1.initPostcssPlugin)({
uniApp: (0, uni_cli_shared_1.parseRpx2UnitOnce)(inputDir, process.env.UNI_PLATFORM),
}),
},
},
optimizeDeps: {
entries: (0, uni_cli_shared_1.resolveMainPathOnce)(inputDir),
exclude: ssr_1.external,
esbuildOptions: {
plugins: [(0, esbuildPrePlugin_1.esbuildPrePlugin)()],
},
},
define: (0, utils_1.createDefine)(env.command, config),
server,
ssr: {
external: ssrExternal,
...(bundleWebVaporSsr ? { noExternal: ssr_1.webVaporSsrNoExternal } : {}),
},
build: {
target: process.env.UNI_APP_X === 'true'
? ['es2015', 'edge79', 'firefox62', 'chrome64', 'safari11.1']
: undefined,
rollupOptions: {
// resolveSSRExternal 会判定package.json,hbx 工程可能没有,通过 rollup 来配置
external: ssr ? ssrExternal : [],
output: {
sourcemapPathTransform,
chunkFileNames(chunkInfo) {
const hash =
// 为了测试额外加的逻辑,避免因为环境不一致导致hash有变化
process.env.UNI_WEB_DISABLE_CHUNK_HASH === 'true'
? ''
: '.[hash]';
const { assetsDir } = options.resolvedConfig.build;
if (chunkInfo.facadeModuleId) {
const dirname = (0, uni_cli_shared_1.normalizePath)(path_1.default.relative(inputDir, path_1.default.dirname(chunkInfo.facadeModuleId)));
if (dirname) {
// 保留workers的目录结构,目前不支持不同的workers引入同一个uts文件,因为目前不能很好的分别打包进各自的chunk中
const workersRootDir = (0, uni_cli_shared_1.getWorkersRootDirs)();
if (workersRootDir.length) {
if (workersRootDir.some((workersRootDir) => dirname.startsWith(workersRootDir))) {
return `${dirname}/[name].js`;
}
}
return path_1.default.posix.join(assetsDir, dirname.replace(/\//g, '-') + `-[name]${hash}.js`);
}
}
return path_1.default.posix.join(assetsDir, `[name]${hash}.js`);
},
},
},
},
};
};
}
exports.createConfig = createConfig;
function resolveManifestServerOptions(inputDir) {
const server = (0, uni_cli_shared_1.getDevServerOptions)((0, uni_cli_shared_1.parseManifestJsonOnce)(inputDir));
// 约定 https: true 时启用 basic-ssl,由插件补齐实际证书内容。
const enableBasicSsl = server.https === true;
const basicSslOptions = enableBasicSsl
? normalizeManifestBasicSslOptions(server.basicSsl)
: undefined;
// basicSsl 仅作为内置插件的扩展配置使用,不能直接透传给 Vite 的 server 配置。
if (enableBasicSsl && (0, shared_1.hasOwn)(server, 'basicSsl')) {
delete server.basicSsl;
}
return {
server,
basicSslOptions,
enableBasicSsl,
};
}
exports.resolveManifestServerOptions = resolveManifestServerOptions;
function normalizeManifestBasicSslOptions(basicSsl) {
if (!(0, shared_1.isPlainObject)(basicSsl)) {
return;
}
// 仅保留 basic-ssl 已支持的字段,避免把无效配置带入插件。
const options = {};
if (typeof basicSsl.name === 'string') {
options.name = basicSsl.name;
}
if (Array.isArray(basicSsl.domains)) {
options.domains = basicSsl.domains.filter((domain) => typeof domain === 'string');
}
if (typeof basicSsl.certDir === 'string') {
options.certDir = basicSsl.certDir;
}
return Object.keys(options).length ? options : undefined;
}
function transformSourcemapPath(relativeSourcePath, sourcemapPath) {
const sourcePath = (0, uni_cli_shared_1.normalizePath)(path_1.default.relative(process.env.UNI_INPUT_DIR, path_1.default.resolve(path_1.default.dirname(sourcemapPath), relativeSourcePath)));
if (sourcePath.startsWith('..')) {
return '';
}
return sourcePath;
}
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function createConfigureServer(): Plugin['configureServer'];
@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createConfigureServer = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const timestamp_1 = require("./middlewares/timestamp");
const ssr_1 = require("./ssr");
const static_1 = require("./static");
function createConfigureServer() {
return function (server) {
(0, ssr_1.initSSR)(server);
const routerOptions = (0, uni_cli_shared_1.getRouterOptions)((0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR));
if (routerOptions.mode === 'history') {
server.middlewares.use((0, timestamp_1.uniTimestampMiddleware)(server));
}
return () => {
(0, static_1.initStatic)(server);
};
};
}
exports.createConfigureServer = createConfigureServer;
@@ -0,0 +1,9 @@
/// <reference types="node" />
import type { IncomingMessage, ServerResponse } from 'http';
interface UniStaticMiddlewareOptions {
etag: boolean;
resolve: (pathname: string) => string | void;
}
export type NextHandler = () => void | Promise<void>;
export declare function uniStaticMiddleware(opts: UniStaticMiddlewareOptions): (req: IncomingMessage, res: ServerResponse, next: NextHandler) => void | Promise<void> | ServerResponse<IncomingMessage>;
export {};
@@ -0,0 +1,80 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniStaticMiddleware = void 0;
const fs_1 = __importDefault(require("fs"));
const url_1 = __importDefault(require("url"));
const lite_1 = __importDefault(require("mime/lite"));
function normalizeFile(filename, isEtag) {
const stats = fs_1.default.statSync(filename);
return {
stats,
headers: normalizeHeaders(filename, stats, isEtag),
};
}
function normalizeHeaders(filename, stats, isEtag) {
const headers = {
'Content-Length': stats.size,
'Content-Type': lite_1.default.getType(filename) || '',
'Last-Modified': stats.mtime.toUTCString(),
};
if (isEtag) {
headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
}
return headers;
}
function send(req, res, filename, stats, headers) {
let code = 200;
headers = { ...headers };
const opts = {};
for (const key in headers) {
const value = res.getHeader(key);
if (value) {
headers[key] = value;
}
}
if (res.getHeader('content-type')) {
headers['Content-Type'] = res.getHeader('content-type');
}
if (req.headers.range) {
code = 206;
const [x, y] = req.headers.range.replace('bytes=', '').split('-');
const end = (opts.end = parseInt(y, 10) || stats.size - 1);
const start = (opts.start = parseInt(x, 10) || 0);
if (start >= stats.size || end >= stats.size) {
res.setHeader('Content-Range', `bytes */${stats.size}`);
res.statusCode = 416;
return res.end();
}
headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
headers['Content-Length'] = end - start + 1;
headers['Accept-Ranges'] = 'bytes';
}
res.writeHead(code, headers);
fs_1.default.createReadStream(filename, opts).pipe(res);
}
function uniStaticMiddleware(opts) {
const isEtag = !!opts.etag;
return function staticMiddleware(req, res, next) {
const pathname = url_1.default.parse(req.url).pathname;
if (!pathname) {
return next();
}
const filename = opts.resolve(pathname);
if (!filename) {
return next();
}
const data = normalizeFile(filename, isEtag);
if (!data) {
return next();
}
if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
res.writeHead(304);
return res.end();
}
return send(req, res, filename, data.stats, data.headers);
};
}
exports.uniStaticMiddleware = uniStaticMiddleware;
@@ -0,0 +1,5 @@
/// <reference types="node" />
import type { IncomingMessage, ServerResponse } from 'http';
import type { ViteDevServer } from 'vite';
import type { NextHandler } from './static';
export declare function uniTimestampMiddleware(server: ViteDevServer): (req: IncomingMessage, _: ServerResponse, next: NextHandler) => Promise<void>;
@@ -0,0 +1,36 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniTimestampMiddleware = void 0;
const url_1 = require("url");
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function uniTimestampMiddleware(server) {
return async function timestampMiddleware(req, _, next) {
// 当页面被作为组件引用时,会导致history刷新该页面直接显示js代码,因为该页面已被缓存为了module,
// https://github.com/vitejs/vite/blob/702d50315535c189151c67d33e4a22124f926bed/packages/vite/src/node/server/transformRequest.ts#L52
// /pages/tabBar/API/API
let { url } = req;
if (url) {
const base = server.config.base;
const parsed = (0, url_1.parse)(url);
let newUrl = url;
if ((parsed.pathname || '/').startsWith(base)) {
newUrl = newUrl.replace(base, '/');
}
if (!path_1.default.extname(newUrl) &&
!newUrl.endsWith('/') &&
!newUrl.includes('?')) {
const module = await server.moduleGraph.getModuleByUrl(newUrl);
if (module && module.file && uni_cli_shared_1.EXTNAME_VUE_RE.test(module.file)) {
// /pages/tabBar/API/API => /pages/tabBar/API/API?__t__=time
req.url = url + '?__t__=' + Date.now();
}
}
}
next();
};
}
exports.uniTimestampMiddleware = uniTimestampMiddleware;
@@ -0,0 +1,6 @@
import type { ViteDevServer } from 'vite';
export declare const external: string[];
export declare const webVaporSsrNoExternal: string[];
export declare function getSsrExternalModules(): string[];
export declare function getWebVaporSsrExternalModules(): string[];
export declare function initSSR(server: ViteDevServer): void;
@@ -0,0 +1,84 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initSSR = exports.getWebVaporSsrExternalModules = exports.getSsrExternalModules = exports.webVaporSsrNoExternal = exports.external = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
exports.external = [
'@dcloudio/uni-app',
'@dcloudio/uni-app-plus',
'@dcloudio/uni-cloud',
'@dcloudio/uni-components',
'@dcloudio/uni-h5',
'@dcloudio/uni-h5-vue',
'@dcloudio/uni-i18n',
'@dcloudio/uni-mp-alipay',
'@dcloudio/uni-mp-baidu',
'@dcloudio/uni-mp-kuaishou',
'@dcloudio/uni-mp-lark',
'@dcloudio/uni-mp-qq',
'@dcloudio/uni-mp-toutiao',
'@dcloudio/uni-mp-weixin',
'@dcloudio/uni-quickapp-webview',
'@dcloudio/uni-shared',
'@dcloudio/uni-stat',
'@dcloudio/uni-stacktracey',
'@vue/shared',
'vue',
'vue-i18n',
'vue-router',
'vuex',
// dev
'@dcloudio/types',
'@dcloudio/uni-automator',
'@dcloudio/uni-cli-shared',
'@dcloudio/vite-plugin-uni',
'autoprefixer',
'typescript',
'vite',
];
// Web Vapor SSR 必须将共享同一 Vue runtime 的依赖打进服务端产物,
// 其他依赖仍保持原有 external 行为,避免影响开发者的 Node 依赖。
exports.webVaporSsrNoExternal = [
'@dcloudio/uni-app',
'@dcloudio/uni-h5',
'@dcloudio/uni-h5-vue',
'@dcloudio/uni-shared',
'@vue/runtime-dom',
'@vue/server-renderer',
'@vue/shared',
'vue',
'vue-i18n',
'vue-router',
'vuex',
];
const webVaporSsrNoExternalSet = new Set(exports.webVaporSsrNoExternal);
function getSsrExternalModules() {
return (0, uni_cli_shared_1.isUniAppXWebVapor)()
? exports.external.filter((id) => id !== '@dcloudio/uni-h5')
: exports.external;
}
exports.getSsrExternalModules = getSsrExternalModules;
function getWebVaporSsrExternalModules() {
return exports.external.filter((id) => !webVaporSsrNoExternalSet.has(id));
}
exports.getWebVaporSsrExternalModules = getWebVaporSsrExternalModules;
function initSSR(server) {
const { ssrLoadModule } = server;
let added = false;
server.ssrLoadModule = (url) => {
const res = ssrLoadModule(url);
if (!added) {
// HBuilderX项目,根目录可能没有package.json,导致 ssrExternals 不生效
added = true;
if (server._ssrExternals) {
const { _ssrExternals } = server;
getSsrExternalModules().forEach((module) => {
if (!_ssrExternals.includes(module)) {
_ssrExternals.push(module);
}
});
}
}
return res;
};
}
exports.initSSR = initSSR;
@@ -0,0 +1,8 @@
import type { ViteDevServer } from 'vite';
/**
* devServer时提供static等目录的静态资源服务
* @param server
* @param param
*/
export declare const initStatic: (server: ViteDevServer) => void;
export declare function createPublicFileFilter(base?: string): (id: unknown) => boolean;
@@ -0,0 +1,59 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPublicFileFilter = exports.initStatic = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const debug_1 = __importDefault(require("debug"));
const pluginutils_1 = require("@rollup/pluginutils");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const static_1 = require("./middlewares/static");
const debugStatic = (0, debug_1.default)('uni:static');
/**
* devServer时提供static等目录的静态资源服务
* @param server
* @param param
*/
const initStatic = (server) => {
const filter = createPublicFileFilter();
const serve = (0, static_1.uniStaticMiddleware)({
etag: true,
resolve(pathname) {
if (!filter(pathname)) {
return;
}
const filename = path_1.default.join(process.env.UNI_INPUT_DIR, pathname);
if (fs_1.default.existsSync(filename)) {
debugStatic(filename, 'success');
return filename;
}
else {
debugStatic(filename, 'fail');
}
},
});
const viteServePublicMiddlewareIndex = server.middlewares.stack.findIndex((middleware) => {
return (middleware.handle.name === 'viteServePublicMiddleware');
});
// 替换 vite 自带的 public middleware
if (viteServePublicMiddlewareIndex > -1) {
server.middlewares.stack.splice(viteServePublicMiddlewareIndex, 1, {
route: '',
handle: ((req, res, next) => {
if ((0, uni_cli_shared_1.isImportRequest)(req.url) || (0, uni_cli_shared_1.isInternalRequest)(req.url)) {
return next();
}
return serve(req, res, next);
}),
});
}
};
exports.initStatic = initStatic;
function createPublicFileFilter(base = '/') {
const publicDir = (0, uni_cli_shared_1.normalizePath)(path_1.default.join(base, uni_cli_shared_1.PUBLIC_DIR + '/**/*'));
const uniModulesDir = (0, uni_cli_shared_1.normalizePath)(path_1.default.join(base, 'uni_modules/*/' + uni_cli_shared_1.PUBLIC_DIR + '/**/*'));
return (0, pluginutils_1.createFilter)([publicDir, uniModulesDir]);
}
exports.createPublicFileFilter = createPublicFileFilter;
@@ -0,0 +1,3 @@
import type { Plugin } from 'esbuild';
export declare const JS_TYPES_RE: RegExp;
export declare function esbuildPrePlugin(): Plugin;
@@ -0,0 +1,33 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.esbuildPrePlugin = exports.JS_TYPES_RE = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
exports.JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/;
function esbuildPrePlugin() {
return {
name: 'uni:dep-scan',
setup(build) {
build.onLoad({ filter: exports.JS_TYPES_RE }, ({ path: id }) => {
let ext = path_1.default.extname(id).slice(1);
if (ext === 'mjs')
ext = 'js';
if (fs_1.default.existsSync(id)) {
let contents = fs_1.default.readFileSync(id, 'utf-8');
if (contents.includes('#endif')) {
contents = (0, uni_cli_shared_1.preJs)(contents, id);
}
return {
loader: ext,
contents,
};
}
});
},
};
}
exports.esbuildPrePlugin = esbuildPrePlugin;
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function createHandleHotUpdate(): Plugin['handleHotUpdate'];
@@ -0,0 +1,86 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createHandleHotUpdate = void 0;
const path_1 = __importDefault(require("path"));
const debug_1 = __importDefault(require("debug"));
const shared_1 = require("@vue/shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../../utils");
const debugHmr = (0, debug_1.default)('uni:hmr');
async function invalidate(file, moduleGraph) {
const mods = await moduleGraph.getModulesByFile((0, uni_cli_shared_1.normalizePath)(file));
if (mods && mods.size) {
;
[...mods].forEach((mod) => {
debugHmr('invalidate', mod.id);
moduleGraph.invalidateModule(mod);
});
}
}
let invalidateFiles;
function createHandleHotUpdate() {
return async function ({ file, server }) {
const inputDir = process.env.UNI_INPUT_DIR;
const platform = process.env.UNI_PLATFORM;
if (!invalidateFiles) {
invalidateFiles = [
path_1.default.resolve(inputDir, uni_cli_shared_1.PAGES_JSON_JS),
path_1.default.resolve(inputDir, uni_cli_shared_1.MANIFEST_JSON_JS),
(0, uni_cli_shared_1.resolveBuiltIn)('@dcloudio/uni-h5/' + (0, utils_1.resolveFrameworkDistDir)() + '/uni-h5.es.js'),
];
try {
invalidateFiles.push((0, uni_cli_shared_1.resolveBuiltIn)('vite/dist/client/env.mjs'));
}
catch (e) { }
}
// TODO 目前简单处理,当pages.json,manifest.json发生变化,就直接刷新,理想情况下,应该区分变化的内容,仅必要时做整页面刷新
const isPagesJson = file.endsWith('pages.json');
const isManifestJson = file.endsWith('manifest.json');
if (!isPagesJson && !isManifestJson) {
return;
}
debugHmr(file);
const pagesJson = (0, uni_cli_shared_1.parsePagesJson)(inputDir, platform);
// 更新define
const { define, server: { middlewareMode }, } = server.config;
(0, shared_1.extend)(define, (0, uni_cli_shared_1.initFeatures)({
inputDir,
command: 'serve',
platform,
pagesJson,
manifestJson: (0, uni_cli_shared_1.parseManifestJson)(inputDir),
ssr: !!middlewareMode,
}));
debugHmr('define', define);
if (isPagesJson) {
const easycom = pagesJson.easycom || {};
const { easyComOptions, refresh } = (0, uni_cli_shared_1.initEasycomsOnce)(inputDir, {
dirs: (0, uni_cli_shared_1.resolveComponentsLibDirs)(),
platform,
isX: process.env.UNI_APP_X === 'true',
});
if (!equal({ autoscan: easycom.autoscan, custom: easycom.custom }, {
autoscan: easyComOptions.autoscan,
custom: easyComOptions.custom,
})) {
refresh();
}
}
// 当pages.json,manifest.json发生变化时,作废pages.json.js缓存
for (const file of invalidateFiles) {
await invalidate(file, server.moduleGraph);
}
server.ws.send({
type: 'full-reload',
path: '*',
});
return [];
};
}
exports.createHandleHotUpdate = createHandleHotUpdate;
function equal(obj1, obj2) {
return JSON.stringify(obj1) === JSON.stringify(obj2);
}
@@ -0,0 +1,2 @@
import type { UniVitePlugin } from '@dcloudio/uni-cli-shared';
export declare function uniH5Plugin(): UniVitePlugin;
+25
View File
@@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniH5Plugin = void 0;
const handleHotUpdate_1 = require("./handleHotUpdate");
const transformIndexHtml_1 = require("./transformIndexHtml");
const configureServer_1 = require("./configureServer");
const uni_1 = require("./uni");
const config_1 = require("./config");
function uniH5Plugin() {
const configOptions = {
resolvedConfig: null,
};
return {
name: 'uni:h5',
uni: (0, uni_1.createUni)(),
config: (0, config_1.createConfig)(configOptions),
configResolved(config) {
configOptions.resolvedConfig = config;
},
configureServer: (0, configureServer_1.createConfigureServer)(),
handleHotUpdate: (0, handleHotUpdate_1.createHandleHotUpdate)(),
transformIndexHtml: (0, transformIndexHtml_1.createTransformIndexHtml)(configOptions),
};
}
exports.uniH5Plugin = uniH5Plugin;
@@ -0,0 +1,4 @@
import type { Plugin, ResolvedConfig } from 'vite';
export declare function createTransformIndexHtml(options: {
resolvedConfig: ResolvedConfig | null;
}): Plugin['transformIndexHtml'];
@@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTransformIndexHtml = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../../utils");
function createTransformIndexHtml(options) {
let warned = false;
return async function (html) {
const manifestJson = (0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR);
const webManifest = (0, uni_cli_shared_1.getPlatformManifestJson)(manifestJson, 'h5');
const title = webManifest?.title || manifestJson.name || '';
const isX = process.env.UNI_APP_X === 'true';
if (isX) {
// 兼容旧版本模板
const mainJs = ` src="/main.js"`;
const mainTs = ` src="/main.ts"`;
const main = ` src="/main"`;
let oldMain = '';
if (html.includes(mainJs)) {
oldMain = mainJs;
}
else if (html.includes(mainTs)) {
oldMain = mainTs;
}
if (oldMain) {
html = html.replace(oldMain, main);
if (!warned) {
warned = true;
console.warn(`当前项目根目录 index.html 未兼容 uni-app x 的 web 平台,请将里边的${oldMain} 调整为${main}。`);
}
}
}
const config = options.resolvedConfig;
if ((0, uni_cli_shared_1.isUniAppXWebVapor)() &&
config &&
!(0, uni_cli_shared_1.isSsr)(config.command, config) &&
!(0, utils_1.isSsrManifest)(config.command, config)) {
html = html.replace('<!--app-html-->', '');
}
const tags = [];
if (process.env.NODE_ENV === 'development') {
tags.push({
tag: 'script',
children: `if (typeof globalThis === 'undefined') {
window.globalThis = window
}`,
injectTo: 'head-prepend',
});
}
return {
html: html.replace(/<title>(.*?)<\/title>/, `<title>${title}</title>`),
tags,
};
};
}
exports.createTransformIndexHtml = createTransformIndexHtml;
@@ -0,0 +1,2 @@
import type { NodeTransform } from '@vue/compiler-core';
export declare const transformAttributePart: NodeTransform;
@@ -0,0 +1,105 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformAttributePart = void 0;
const uni_shared_1 = require("@dcloudio/uni-shared");
const compiler_core_1 = require("@vue/compiler-core");
const transformAttributePart = (node, context) => {
if (node.type !== compiler_core_1.NodeTypes.ELEMENT) {
return;
}
const staticClassProp = node.props.find((prop) => prop.type === compiler_core_1.NodeTypes.ATTRIBUTE && prop.name === 'class');
const dynamicClassProp = node.props.find((prop) => prop.type === compiler_core_1.NodeTypes.DIRECTIVE &&
prop.arg?.type === compiler_core_1.NodeTypes.SIMPLE_EXPRESSION &&
prop.arg.content === 'class');
node.props.forEach((prop) => {
// 将part属性计算后添加到class中,支持动态part,支持多part
if (prop.type === compiler_core_1.NodeTypes.ATTRIBUTE && prop.name === 'part') {
// 静态part属性
const partClasses = (0, uni_shared_1.batchGetPartClass)(prop.value?.content || '');
if (staticClassProp) {
// 已有静态class属性
staticClassProp.value.content += ` ${partClasses}`;
}
else if (dynamicClassProp) {
// 已有动态class属性
dynamicClassProp.exp = (0, compiler_core_1.createCompoundExpression)([
dynamicClassProp.exp,
` + ' ${partClasses}'`,
]);
}
else {
// 无class属性
node.props.push({
type: compiler_core_1.NodeTypes.ATTRIBUTE,
name: 'class',
value: {
type: compiler_core_1.NodeTypes.TEXT,
content: partClasses,
loc: compiler_core_1.locStub,
},
loc: compiler_core_1.locStub,
nameLoc: compiler_core_1.locStub,
});
}
}
else if (prop.type === compiler_core_1.NodeTypes.DIRECTIVE &&
prop.arg?.type === compiler_core_1.NodeTypes.SIMPLE_EXPRESSION &&
prop.arg.content === 'part') {
// 动态part属性
// TODO 使用uni-shared内的getPartClass
const partClassExp = (0, compiler_core_1.createCompoundExpression)([
`(`,
prop.exp,
`).split(/\\s+/).filter(Boolean).map(partName => \`-_part__\${partName}_-\`).join(' ')`,
]);
if (staticClassProp) {
// 已有静态class属性,需要转为动态class属性
node.props.splice(node.props.indexOf(staticClassProp), 1);
node.props.push({
type: compiler_core_1.NodeTypes.DIRECTIVE,
name: 'bind',
exp: (0, compiler_core_1.createCompoundExpression)([
staticClassProp.value.content,
`+ ' ' +`,
partClassExp,
]),
arg: {
type: compiler_core_1.NodeTypes.SIMPLE_EXPRESSION,
content: 'class',
isStatic: true,
loc: compiler_core_1.locStub,
constType: compiler_core_1.ConstantTypes.NOT_CONSTANT,
},
loc: compiler_core_1.locStub,
modifiers: [],
});
}
else if (dynamicClassProp) {
// 已有动态class属性
dynamicClassProp.exp = (0, compiler_core_1.createCompoundExpression)([
dynamicClassProp.exp,
` + ' ' +`,
partClassExp,
]);
}
else {
// 无class属性
node.props.push({
type: compiler_core_1.NodeTypes.DIRECTIVE,
name: 'bind',
exp: partClassExp,
arg: {
type: compiler_core_1.NodeTypes.SIMPLE_EXPRESSION,
content: 'class',
isStatic: true,
loc: compiler_core_1.locStub,
constType: compiler_core_1.ConstantTypes.NOT_CONSTANT,
},
loc: compiler_core_1.locStub,
modifiers: [],
});
}
}
});
};
exports.transformAttributePart = transformAttributePart;
@@ -0,0 +1,2 @@
import { type NodeTransform } from '@vue/compiler-core';
export declare const transformCustomElement: NodeTransform;
@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformCustomElement = void 0;
const compiler_core_1 = require("@vue/compiler-core");
const uni_shared_1 = require("@dcloudio/uni-shared");
const transformCustomElement = (node, context) => {
if (!!node &&
node.type === compiler_core_1.NodeTypes.ELEMENT &&
uni_shared_1.UVUE_WEB_BUILT_IN_CUSTOM_ELEMENTS.includes(node.tag)) {
node.tag = `$UniCustomElement$${node.tag}`;
}
};
exports.transformCustomElement = transformCustomElement;
@@ -0,0 +1,2 @@
import type { NodeTransform } from '@vue/compiler-core';
export declare const transformPageHead: NodeTransform;
@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformPageHead = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const compiler_core_1 = require("@vue/compiler-core");
const transformPageHead = (node, context) => {
if ((0, uni_cli_shared_1.checkElementNodeTag)(node, 'page-meta')) {
const headNode = node.children.find((child) => (0, uni_cli_shared_1.checkElementNodeTag)(child, 'head'));
if (headNode) {
headNode.tag = 'page-meta-head';
headNode.tagType = compiler_core_1.ElementTypes.COMPONENT;
}
return;
}
if ((0, uni_cli_shared_1.checkElementNodeTag)(node, 'head') &&
(0, uni_cli_shared_1.checkElementNodeTag)(context.parent, 'page-meta')) {
;
node.tag = 'page-meta-head';
node.tagType = compiler_core_1.ElementTypes.COMPONENT;
}
};
exports.transformPageHead = transformPageHead;
+11
View File
@@ -0,0 +1,11 @@
import { type UniVitePlugin } from '@dcloudio/uni-cli-shared';
import { isH5NativeTag } from '@dcloudio/uni-shared';
declare function realIsH5CustomElement(tag: string): boolean;
export declare const compilerOptions: {
isNativeTag: typeof isH5NativeTag;
isCustomElement: typeof realIsH5CustomElement;
nodeTransforms: import("@vue/compiler-core").NodeTransform[];
ssrPreTagTransforms: import("@vue/compiler-core").NodeTransform[];
};
export declare function createUni(): UniVitePlugin['uni'];
export {};
+52
View File
@@ -0,0 +1,52 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createUni = exports.compilerOptions = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const uni_shared_1 = require("@dcloudio/uni-shared");
const transformCustomElement_1 = require("./transforms/transformCustomElement");
const transformAttributePart_1 = require("./transforms/transformAttributePart");
const transformPageHead_1 = require("./transforms/transformPageHead");
function realIsH5CustomElement(tag) {
// TODO isH5CustomElement目前被多个平台引用,重构比较麻烦
if (process.env.UNI_APP_X === 'true' &&
uni_shared_1.UVUE_WEB_BUILT_IN_CUSTOM_ELEMENTS.includes(tag) &&
!(0, uni_cli_shared_1.isUniAppXWebVapor)()) {
return true;
}
return (0, uni_shared_1.isH5CustomElement)(tag, process.env.UNI_APP_X === 'true');
}
const nodeTransforms = [
uni_cli_shared_1.transformRefresherSlot,
uni_cli_shared_1.transformH5BuiltInComponents,
uni_cli_shared_1.transformTapToClick,
uni_cli_shared_1.transformMatchMedia,
uni_cli_shared_1.transformPageHead,
];
if (process.env.UNI_APP_X === 'true') {
// uni-app x 的 Vapor 使用 UVue 组件,非 Vapor 使用注册的 Custom Element。
nodeTransforms.splice(nodeTransforms.indexOf(uni_cli_shared_1.transformMatchMedia), 1);
if (!(0, uni_cli_shared_1.isUniAppXWebVapor)()) {
nodeTransforms.push(transformCustomElement_1.transformCustomElement);
}
if (process.env.UNI_UTS_PLATFORM === 'web') {
nodeTransforms.push(transformAttributePart_1.transformAttributePart);
}
}
exports.compilerOptions = {
isNativeTag: uni_shared_1.isH5NativeTag,
isCustomElement: realIsH5CustomElement,
nodeTransforms,
ssrPreTagTransforms: [uni_cli_shared_1.transformH5BuiltInComponents, transformPageHead_1.transformPageHead],
};
function createUni() {
return {
copyOptions: {
assets: ['hybrid/html/**/*', 'uni_modules/*/hybrid/html/**/*'],
},
compilerOptions: exports.compilerOptions,
jsxOptions: {
babelPlugins: [uni_cli_shared_1.transformUniH5Jsx],
},
};
}
exports.createUni = createUni;
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniApiPlugin(): Plugin;
+79
View File
@@ -0,0 +1,79 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniApiPlugin = void 0;
const utils_1 = require("../utils");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
let enableFacialRecognition = false;
function isEnableFacialRecognition() {
return enableFacialRecognition;
}
function setEnableFacialRecognition(enable) {
enableFacialRecognition = enable;
}
function checkGetMetaInfo(code) {
return code.includes('window.getMetaInfo');
}
function checkFacialRecognition(code) {
return code.includes('getFacialRecognitionMetaInfo');
}
function uniApiPlugin() {
let viteServer = undefined;
const inputDir = (0, uni_cli_shared_1.normalizePath)(process.env.UNI_INPUT_DIR);
return {
name: 'uni:h5-api',
enforce: 'pre',
configureServer(server) {
viteServer = server;
},
transform(code, id) {
if (!viteServer)
return;
// 通过transform阶段识别,仅判断inputDir内部的文件,避免框架文件影响
if (!isEnableFacialRecognition() &&
(0, uni_cli_shared_1.normalizePath)(id).startsWith(inputDir)) {
if (checkFacialRecognition(code)) {
setEnableFacialRecognition(true);
// 开发模式触发重新刷新
viteServer.hot.send({
type: 'full-reload',
path: '*',
});
}
}
},
generateBundle(_options, bundle) {
if (viteServer)
return;
if (!isEnableFacialRecognition()) {
const filesNames = Object.keys(bundle);
for (const fileName of filesNames) {
const chunk = bundle[fileName];
if (chunk &&
chunk.type === 'chunk' &&
chunk.code &&
!isEnableFacialRecognition()) {
setEnableFacialRecognition(checkFacialRecognition(chunk.code) || checkGetMetaInfo(chunk.code));
}
}
}
},
transformIndexHtml: {
order: 'post',
handler() {
if (!isEnableFacialRecognition()) {
return;
}
return [
{
tag: 'script',
attrs: {
src: utils_1.AliYunCloudAuthWebSDK,
},
injectTo: 'head',
},
];
},
},
};
}
exports.uniApiPlugin = uniApiPlugin;
+27
View File
@@ -0,0 +1,27 @@
import { type Plugin } from 'vite';
import type { OutputOptions } from 'rollup';
export declare function uniCssPlugin(): Plugin;
/**
* converts the source filepath of the asset to the output filename based on the assetFileNames option. \
* this function imitates the behavior of rollup.js. \
* https://rollupjs.org/guide/en/#outputassetfilenames
*
* @example
* ```ts
* const content = Buffer.from('text');
* const fileName = assetFileNamesToFileName(
* 'assets/[name].[hash][extname]',
* '/path/to/file.txt',
* getAssetHash(content),
* content
* )
* // fileName: 'assets/file.982d9e3e.txt'
* ```
*
* @param assetFileNames filename pattern. e.g. `'assets/[name].[hash][extname]'`
* @param file filepath of the asset
* @param contentHash hash of the asset. used for `'[hash]'` placeholder
* @param content content of the asset. passed to `assetFileNames` if `assetFileNames` is a function
* @returns output filename
*/
export declare function assetFileNamesToFileName(assetFileNames: Exclude<OutputOptions['assetFileNames'], undefined>, file: string, contentHash: string, content: string | Uint8Array): string;
+231
View File
@@ -0,0 +1,231 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.assetFileNamesToFileName = exports.uniCssPlugin = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const vite_1 = require("vite");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const shared_1 = require("@vue/shared");
function isCombineBuiltInCss(config) {
return config.command === 'build' && config.build.cssCodeSplit;
}
function uniCssPlugin() {
let resolvedConfig;
let file = '';
let fileName = '';
let isInternational = false;
return {
name: 'uni:h5-css',
enforce: 'pre',
configResolved(config) {
resolvedConfig = config;
file = path_1.default.join(process.env.UNI_INPUT_DIR, 'uni.css');
isInternational = !!(process.env.UNI_APP_ID && process.env.UNI_APP_ID.startsWith('__UNI__G'));
if (process.env.UNI_COMPILE_TARGET === 'uni_modules') {
(0, uni_cli_shared_1.injectCssPlugin)(config, {
createUrlReplacer: uni_cli_shared_1.createEncryptCssUrlReplacer,
});
(0, uni_cli_shared_1.injectCssPostPlugin)(config, (0, uni_cli_shared_1.cssPostPlugin)(config, {
platform: process.env.UNI_PLATFORM,
preserveModules: true,
chunkCssFilename(id) {
if ((0, uni_cli_shared_1.isVueSfcFile)(id)) {
return ((0, uni_cli_shared_1.removeExt)((0, vite_1.normalizePath)(path_1.default.relative(process.env.UNI_INPUT_DIR, id))) + '.css');
}
},
chunkCssCode(_filename, cssCode) {
return cssCode;
},
}));
(0, uni_cli_shared_1.injectAssetPlugin)(config);
}
},
transform(code, id) {
id = (0, vite_1.normalizePath)(id);
const fieldStyle = resolveH5FieldStyle(id);
if (fieldStyle) {
this.addWatchFile(fieldStyle);
return {
code: code + '\n' + fs_1.default.readFileSync(fieldStyle, 'utf8'),
map: { mappings: '' },
};
}
if (id.endsWith(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'shadow.css') &&
process.env.NODE_ENV !== 'development') {
const url = (0, uni_cli_shared_1.createShadowImageUrl)(0, 'grey', isInternational);
return {
code: code +
`
@keyframes shadow-preload {
0% {
background-image: url(${url});
}
100% {
background-image: url(${url});
}
}
`,
map: { mappings: '' },
};
}
else if (id.endsWith(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'pageHead.css')) {
return {
code: code +
`
.uni-page-head-shadow-grey::after {
background-image: url('${(0, uni_cli_shared_1.createShadowImageUrl)(0, 'grey', isInternational)}');
}
.uni-page-head-shadow-blue::after {
background-image: url('${(0, uni_cli_shared_1.createShadowImageUrl)(0, 'blue', isInternational)}');
}
.uni-page-head-shadow-green::after {
background-image: url('${(0, uni_cli_shared_1.createShadowImageUrl)(0, 'green', isInternational)}');
}
.uni-page-head-shadow-orange::after {
background-image: url('${(0, uni_cli_shared_1.createShadowImageUrl)(0, 'orange', isInternational)}');
}
.uni-page-head-shadow-red::after {
background-image: url('${(0, uni_cli_shared_1.createShadowImageUrl)(0, 'red', isInternational)}');
}
.uni-page-head-shadow-yellow::after {
background-image: url('${(0, uni_cli_shared_1.createShadowImageUrl)(0, 'yellow', isInternational)}');
}
`,
map: { mappings: '' },
};
}
},
async generateBundle() {
if (!isCombineBuiltInCss(resolvedConfig) || !uni_cli_shared_1.buildInCssSet.size) {
return;
}
// 生成框架css(需要排序,避免生成不一样的内容)
const content = await (0, uni_cli_shared_1.minifyCSS)(generateBuiltInCssCode([...uni_cli_shared_1.buildInCssSet].sort()), resolvedConfig);
// 'Buffer' only refers to a type, but is being used as a value here
const contentHash = (0, uni_cli_shared_1.getAssetHash)(Buffer.from(content, 'utf-8'));
const assetFileNames = path_1.default.posix.join(resolvedConfig.build.assetsDir, '[name].[hash][extname]');
fileName = assetFileNamesToFileName(assetFileNames, file, contentHash, content);
const name = (0, vite_1.normalizePath)(path_1.default.relative(resolvedConfig.root, file));
this.emitFile({
name,
fileName,
type: 'asset',
source: content,
});
},
transformIndexHtml: {
order: 'post',
handler() {
if (!fileName) {
return;
}
// 追加框架css
return [
{
tag: 'link',
attrs: {
rel: 'stylesheet',
href: toPublicPath(fileName, resolvedConfig),
},
injectTo: 'head-prepend',
},
];
},
},
};
}
exports.uniCssPlugin = uniCssPlugin;
function toPublicPath(filename, config) {
return (0, uni_cli_shared_1.isExternalUrl)(filename) ? filename : config.base + filename;
}
function generateBuiltInCssCode(cssImports) {
return cssImports
.map((cssImport) => {
const code = fs_1.default.readFileSync((0, uni_cli_shared_1.resolveBuiltIn)(cssImport), 'utf8');
const fieldStyle = resolveH5FieldStyle(cssImport);
return fieldStyle
? code + '\n' + fs_1.default.readFileSync(fieldStyle, 'utf8')
: code;
})
.join('\n');
}
function resolveH5FieldStyle(id) {
// Vite's load hook has already converted raw and URL requests to JavaScript.
if (/(?:\?|&)(?:raw|url)(?:&|$)/.test(id)) {
return;
}
const match = /(?:^|\/)uni-components\/style\/+(input|textarea)\.css(?:[?#].*)?$/.exec(id);
if (match) {
return (0, uni_cli_shared_1.resolveBuiltIn)(uni_cli_shared_1.H5_COMPONENTS_STYLE_PATH + match[1] + '.css');
}
}
/**
* converts the source filepath of the asset to the output filename based on the assetFileNames option. \
* this function imitates the behavior of rollup.js. \
* https://rollupjs.org/guide/en/#outputassetfilenames
*
* @example
* ```ts
* const content = Buffer.from('text');
* const fileName = assetFileNamesToFileName(
* 'assets/[name].[hash][extname]',
* '/path/to/file.txt',
* getAssetHash(content),
* content
* )
* // fileName: 'assets/file.982d9e3e.txt'
* ```
*
* @param assetFileNames filename pattern. e.g. `'assets/[name].[hash][extname]'`
* @param file filepath of the asset
* @param contentHash hash of the asset. used for `'[hash]'` placeholder
* @param content content of the asset. passed to `assetFileNames` if `assetFileNames` is a function
* @returns output filename
*/
function assetFileNamesToFileName(assetFileNames, file, contentHash, content) {
const basename = path_1.default.basename(file);
// placeholders for `assetFileNames`
// `hash` is slightly different from the rollup's one
const extname = path_1.default.extname(basename);
const ext = extname.slice(1);
const name = basename.slice(0, -extname.length);
const hash = contentHash;
if ((0, shared_1.isFunction)(assetFileNames)) {
assetFileNames = assetFileNames({
name: file,
originalFileName: file,
source: content,
type: 'asset',
});
if (!(0, shared_1.isString)(assetFileNames)) {
throw new TypeError('assetFileNames must return a string');
}
}
else if (!(0, shared_1.isString)(assetFileNames)) {
throw new TypeError('assetFileNames must be a string or a function');
}
const fileName = assetFileNames.replace(/\[\w+\]/g, (placeholder) => {
switch (placeholder) {
case '[ext]':
return ext;
case '[extname]':
return extname;
case '[hash]':
return hash;
case '[name]':
return name;
}
throw new Error(`invalid placeholder ${placeholder} in assetFileNames "${assetFileNames}"`);
});
return fileName;
}
exports.assetFileNamesToFileName = assetFileNamesToFileName;
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniCustomElementPlugin(): Plugin;
@@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniCustomElementPlugin = void 0;
const shared_1 = require("@vue/shared");
const uni_shared_1 = require("@dcloudio/uni-shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const H5_COMPONENTS_PATH = '@dcloudio/uni-h5';
function uniCustomElementPlugin() {
return {
name: 'uni:h5-custom-element',
transform(code, id) {
if (!(0, uni_cli_shared_1.isVueSfcFile)(id) && !id.includes('vue&type=script')) {
return;
}
if (!code.includes('$UniCustomElement$')) {
return;
}
const importSpecifiers = new Set();
code = code.replace(/['|"]\$UniCustomElement\$([\w|-]+)['|"]/g, (_, name) => {
if (!uni_shared_1.UVUE_WEB_BUILT_IN_CUSTOM_ELEMENTS.includes(name)) {
return _;
}
const elementName = (0, shared_1.capitalize)((0, shared_1.camelize)(name));
const localName = '_' + elementName + 'Element';
importSpecifiers.add(`${elementName} as ${localName}`);
return localName;
});
if (importSpecifiers.size) {
code =
`import {${Array.from(importSpecifiers).join(',')}} from "${H5_COMPONENTS_PATH}";` + code;
}
return {
code,
map: null,
};
},
};
}
exports.uniCustomElementPlugin = uniCustomElementPlugin;
@@ -0,0 +1,10 @@
import type { Plugin } from 'vite';
import { type FilterPattern } from '@rollup/pluginutils';
interface UniEasycomPluginOptions {
include?: FilterPattern;
exclude?: FilterPattern;
vapor?: boolean;
excludeBuiltInComponents?: string[];
}
export declare function uniEasycomPlugin(options: UniEasycomPluginOptions): Plugin;
export {};
+221
View File
@@ -0,0 +1,221 @@
"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 fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const pluginutils_1 = require("@rollup/pluginutils");
const estree_walker_1 = require("estree-walker");
const shared_1 = require("@vue/shared");
const uni_shared_1 = require("@dcloudio/uni-shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const H5_COMPONENTS_PATH = '@dcloudio/uni-h5';
const VAPOR_EASYCOM_IMPORT = "import { createComponent as __createEasycomComponent } from 'vue';";
const xBaseComponents = ['slider', 'switch', 'loading', 'page-container'];
// Vapor 未支持组件仅用带 uni-view 的节点显示提示,无需独立 CSS,也不能回退加载旧宿主 CSS。
// 已接入组件的样式优先于此名单;非 Vapor 仍按原路径加载。
const vaporPlaceholderComponents = new Set([
'ad-content-page',
'ad-draw',
'camera',
'live-player',
'live-pusher',
]);
const baseComponents = [
// 'audio',
'button',
'canvas',
'checkbox',
'checkbox-group',
'editor',
'form',
'icon',
'image',
'input',
'label',
'movable-area',
'movable-view',
'navigator',
'picker-view',
'picker-view-column',
'progress',
'radio',
'radio-group',
'resize-sensor',
'refresher',
'rich-text',
'scroll-view',
'slider',
'swiper',
'swiper-item',
'switch',
'text',
'textarea',
'view',
'list-view',
'list-item',
'sticky-section',
'sticky-header',
];
let componentDepsCss;
function uniEasycomPlugin(options) {
const filter = (0, pluginutils_1.createFilter)(options.include, options.exclude);
let needCombineBuiltInCss = false;
componentDepsCss = (0, uni_cli_shared_1.COMPONENT_DEPS_CSS)(process.env.UNI_APP_X === 'true');
const isDevX = process.env.UNI_HX_VERSION_DEV === 'true' &&
process.env.UNI_APP_X === 'true';
const isWebVapor = options.vapor ?? (0, uni_cli_shared_1.isUniAppXWebVapor)();
const excludedComponents = new Set(options.excludeBuiltInComponents);
const isBuiltInComponent = (name) => {
name = name.replace(uni_shared_1.COMPONENT_PREFIX, '');
return (!excludedComponents.has(name) &&
(isWebVapor
? (0, uni_shared_1.isDom2WebVueComponentTag)(name)
: (0, uni_shared_1.isWebBuiltInComponent)(name)));
};
return {
name: 'uni:h5-easycom',
configResolved(config) {
needCombineBuiltInCss = (0, uni_cli_shared_1.isCombineBuiltInCss)(config);
},
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') &&
!(isWebVapor && code.includes('_createAssetComponent'))) {
return;
}
let i = 0;
const importDeclarations = [];
if (isWebVapor && code.includes('_createAssetComponent')) {
const transformed = replaceVaporAssetComponents(code, this.parse(code), isDevX, isBuiltInComponent);
if (transformed !== code) {
code = transformed;
importDeclarations.push(VAPOR_EASYCOM_IMPORT);
}
}
if (!code.includes('_resolveComponent')) {
return;
}
code = code.replace(/_resolveComponent\("(.+?)"(, true)?\)/g, (str, name) => {
if (name && !name.startsWith('_')) {
// 为了兼容性,仅处理dev模式
if (!isDevX) {
const result = buildInComponent();
if (result) {
return result;
}
}
if (isDevX && name.startsWith('v-uni-')) {
name = name.replace('v-uni-', '');
}
const source = (0, uni_cli_shared_1.matchEasycom)(name);
if (source) {
const isHelpers = source.includes('?uni_helpers');
if (isHelpers) {
const cssFilename = path_1.default.join(process.env.UNI_MODULES_ENCRYPT_CACHE_DIR, path_1.default.relative(process.env.UNI_INPUT_DIR, source.replace('?uni_helpers', '/components/' + name + '/' + name + '.css')));
if (fs_extra_1.default.existsSync(cssFilename)) {
importDeclarations.push(`import "${(0, uni_cli_shared_1.normalizePath)(cssFilename)}";`);
}
}
// 处理easycom组件优先级
return (0, uni_cli_shared_1.genResolveEasycomCode)(importDeclarations, str, (0, uni_cli_shared_1.addImportDeclaration)(importDeclarations, `__easycom_${i++}`, source, isHelpers ? (0, shared_1.capitalize)((0, shared_1.camelize)(name)) : ''));
}
if (isDevX) {
const result = buildInComponent();
if (result) {
return result;
}
}
function buildInComponent() {
if (isBuiltInComponent(name)) {
name = name.replace(uni_shared_1.COMPONENT_PREFIX, '');
const local = `__syscom_${i++}`;
if (needCombineBuiltInCss) {
// 发行模式下,应该将内置组件css输出到入口css中
resolveBuiltInCssImport(name, isWebVapor).forEach((cssImport) => uni_cli_shared_1.buildInCssSet.add(cssImport));
return (0, uni_cli_shared_1.addImportDeclaration)(importDeclarations, local, H5_COMPONENTS_PATH, (0, shared_1.capitalize)((0, shared_1.camelize)(name)));
}
return addBuiltInImportDeclaration(importDeclarations, local, name, isWebVapor);
}
}
}
return str;
});
if (importDeclarations.length) {
code = importDeclarations.join('') + code;
}
return {
code,
map: null,
};
},
};
}
exports.uniEasycomPlugin = uniEasycomPlugin;
// 只处理真实调用,并移除 createAssetComponent 独有的尾部参数。
function replaceVaporAssetComponents(code, ast, isDevX, isBuiltInComponent) {
const edits = [];
(0, estree_walker_1.walk)(ast, {
enter(node) {
const call = node;
if (call.type === 'CallExpression' &&
call.callee.type === 'Identifier' &&
call.callee.name === '_createAssetComponent' &&
call.arguments[0]?.type === 'Literal' &&
typeof call.arguments[0].value === 'string') {
const first = call.arguments[0];
const name = first.value;
const easycomName = isDevX && name.startsWith('v-uni-') ? name.slice(6) : name;
if (!name.startsWith('_') &&
(isBuiltInComponent(name) || (0, uni_cli_shared_1.matchEasycom)(easycomName))) {
edits.push([
call.start,
first.end,
`__createEasycomComponent(_resolveComponent(${code.slice(first.start, first.end)})`,
]);
if (call.arguments.length > 5) {
edits.push([call.arguments[4].end, call.end - 1, '']);
}
}
}
},
});
for (const [start, end, replacement] of edits.sort((a, b) => b[0] - a[0])) {
code = code.slice(0, start) + replacement + code.slice(end);
}
return code;
}
function resolveBuiltInCssImport(name, isWebVapor) {
const cssImports = [];
const vaporStyle = isWebVapor && (0, uni_cli_shared_1.resolveWebVaporComponentStyle)(name);
if (vaporStyle) {
cssImports.push(vaporStyle);
}
else if (!isWebVapor || !vaporPlaceholderComponents.has(name)) {
const isX = process.env.UNI_APP_X === 'true';
if (isX && xBaseComponents.includes(name)) {
cssImports.push(uni_cli_shared_1.X_BASE_COMPONENTS_STYLE_PATH + name + '.css');
}
else if (baseComponents.includes(name)) {
cssImports.push(uni_cli_shared_1.BASE_COMPONENTS_STYLE_PATH + name + '.css');
}
else {
cssImports.push(uni_cli_shared_1.H5_COMPONENTS_STYLE_PATH + name + '.css');
}
}
const deps = componentDepsCss[name];
deps && deps.forEach((dep) => cssImports.push(dep));
return cssImports;
}
function addBuiltInImportDeclaration(importDeclarations, local, name, isWebVapor) {
resolveBuiltInCssImport(name, isWebVapor).forEach((cssImport) => importDeclarations.push(`import '${cssImport}';`));
return (0, uni_cli_shared_1.addImportDeclaration)(importDeclarations, local, H5_COMPONENTS_PATH, (0, shared_1.capitalize)((0, shared_1.camelize)(name)));
}
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniInjectPlugin(): Plugin;
+71
View File
@@ -0,0 +1,71 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniInjectPlugin = void 0;
const path_1 = __importDefault(require("path"));
const shared_1 = require("@vue/shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const apiJson = require(path_1.default.resolve(__dirname, process.env.UNI_APP_X === 'true'
? '../../lib/api.x.json'
: '../../lib/api.json'));
const uniInjectPluginOptions = {
exclude: [...uni_cli_shared_1.COMMON_EXCLUDE],
'uni.': [
'@dcloudio/uni-h5',
((method) => apiJson.includes(method)),
],
// 兼容 wx 对象
'wx.': [
'@dcloudio/uni-h5',
((method) => apiJson.includes(method)),
],
getApp: ['@dcloudio/uni-h5', 'getApp'],
getCurrentPages: ['@dcloudio/uni-h5', 'getCurrentPages'],
UniServiceJSBridge: ['@dcloudio/uni-h5', 'UniServiceJSBridge'],
UniViewJSBridge: ['@dcloudio/uni-h5', 'UniViewJSBridge'],
};
function uniInjectPlugin() {
let resolvedConfig;
const apiDepsCss = (0, uni_cli_shared_1.API_DEPS_CSS)(process.env.UNI_APP_X === 'true');
const callback = function (imports, mod) {
const styles = mod[0] === '@dcloudio/uni-h5' &&
apiDepsCss[mod[1]];
if (!styles) {
return;
}
styles.forEach((style) => {
if ((0, uni_cli_shared_1.isCombineBuiltInCss)(resolvedConfig)) {
uni_cli_shared_1.buildInCssSet.add(style);
}
else {
if (!imports.has(style)) {
imports.set(style, `import '${style}';`);
}
}
});
};
let injectPlugin;
return {
name: 'uni:h5-inject',
apply: 'build',
enforce: 'post',
configResolved(config) {
resolvedConfig = config;
const enableTreeShaking = (0, uni_cli_shared_1.isEnableTreeShaking)((0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR));
if (!enableTreeShaking) {
// 不启用摇树优化,移除 wx、uni 等 API 配置
delete uniInjectPluginOptions['wx.'];
delete uniInjectPluginOptions['uni.'];
}
injectPlugin = (0, uni_cli_shared_1.uniViteInjectPlugin)('uni:h5-inject', (0, shared_1.extend)(uniInjectPluginOptions, {
callback,
}));
},
transform(code, id) {
return injectPlugin.transform.call(this, code, id);
},
};
}
exports.uniInjectPlugin = uniInjectPlugin;
@@ -0,0 +1 @@
export declare function uniMainJsPlugin(): import("vite").Plugin<any>;
+64
View File
@@ -0,0 +1,64 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniMainJsPlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../utils");
function uniMainJsPlugin() {
const isWebVapor = (0, uni_cli_shared_1.isUniAppXWebVapor)();
return (0, uni_cli_shared_1.defineUniMainJsPlugin)((opts) => {
let runSSR = false;
return {
name: 'uni:h5-main-js',
enforce: 'pre',
configResolved(config) {
runSSR =
(0, uni_cli_shared_1.isSsr)(config.command, config) || (0, utils_1.isSsrManifest)(config.command, config);
},
transform(code, id, options) {
if (opts.filter(id)) {
if (!runSSR) {
code = code.includes('createSSRApp')
? isWebVapor
? createVaporApp(code)
: createApp(code)
: isWebVapor
? createVaporLegacyApp(code)
: createLegacyApp(code);
}
else {
code = (0, utils_1.isSSR)(options)
? createSSRServerApp(code)
: createSSRClientApp(code, isWebVapor);
}
code = `import './${uni_cli_shared_1.PAGES_JSON_JS}';${code}`;
return {
code,
map: this.getCombinedSourcemap(),
};
}
},
};
});
}
exports.uniMainJsPlugin = uniMainJsPlugin;
function createVaporApp(code) {
return `import { plugin as __plugin } from '@dcloudio/uni-h5';${code.replace('createSSRApp', 'createVaporApp as createSSRApp')};\ncreateApp().app.use(__plugin).mount("#app");`;
}
function createVaporLegacyApp(code) {
return `import { plugin as __plugin } from '@dcloudio/uni-h5';function createApp(rootComponent,rootProps){return createVaporApp(rootComponent, rootProps).use(__plugin)};${code.replace('createApp', 'createVaporApp')}`;
}
function createApp(code) {
return `import { plugin as __plugin } from '@dcloudio/uni-h5';${code.replace('createSSRApp', 'createVueApp as createSSRApp')};\ncreateApp().app.use(__plugin).mount("#app");`;
}
function createLegacyApp(code) {
return `import { plugin as __plugin } from '@dcloudio/uni-h5';function createApp(rootComponent,rootProps){return createVueApp(rootComponent, rootProps).use(__plugin)};${code.replace('createApp', 'createVueApp')}`;
}
function createSSRClientApp(code, isWebVapor) {
if (isWebVapor) {
code = code.replace('createSSRApp', 'createVaporSSRApp as createSSRApp');
}
return `import { plugin as __plugin } from '@dcloudio/uni-h5';import { UNI_SSR, UNI_SSR_STORE } from '@dcloudio/uni-shared';${code};\n// @ts-ignore\nconst { app: __app, store: __store } = createApp();__app.use(__plugin);__store && window[UNI_SSR] && window[UNI_SSR][UNI_SSR_STORE] && __store.replaceState(window[UNI_SSR][UNI_SSR_STORE]);__app.router.isReady().then(() => __app.mount("#app"));`;
}
function createSSRServerApp(code) {
return code;
}
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniManifestJsonPlugin(): Plugin;
@@ -0,0 +1,108 @@
"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: '/',
assets: 'assets',
routerBase: '/',
};
const defaultAsync = {
loading: 'AsyncLoading',
error: 'AsyncError',
delay: 200,
timeout: 60000,
suspensible: true,
};
function uniManifestJsonPlugin() {
return (0, uni_cli_shared_1.defineUniManifestJsonPlugin)((opts) => {
let resolvedConfig;
return {
name: 'uni:h5-manifest-json',
enforce: 'pre',
configResolved(config) {
defaultRouter.assets = config.build.assetsDir;
resolvedConfig = config;
},
transform(code, id) {
if (!opts.filter(id)) {
return;
}
const manifest = (0, uni_cli_shared_1.parseJson)(code, false, id);
const { debug } = manifest;
const h5 = (0, uni_cli_shared_1.getPlatformManifestJson)(manifest, 'h5');
const router = {
...defaultRouter,
...{ base: resolvedConfig.base },
...((h5 && h5.router) || {}),
};
if (!router.base) {
router.base = '/';
}
/**
* ssr时base和访问域名不一致导致跳到错误链接,其实应该区分server和client的部署路径,后续有需求可以加上
*/
router.routerBase = new URL(router.base, 'http://localhost').pathname;
const async = { ...defaultAsync, ...((h5 && h5.async) || {}) };
const networkTimeout = (0, uni_cli_shared_1.normalizeNetworkTimeout)(manifest.networkTimeout);
const sdkConfigs = (h5 && h5.sdkConfigs) || {};
const tempTencentMapKey = sdkConfigs.maps &&
sdkConfigs.maps.tencent &&
sdkConfigs.maps.tencent.key;
const tempQQMapKey = sdkConfigs.maps && sdkConfigs.maps.qqmap && sdkConfigs.maps.qqmap.key;
const qqMapKey = tempTencentMapKey || tempQQMapKey;
const bMapKey = sdkConfigs.maps && sdkConfigs.maps.bmap && sdkConfigs.maps.bmap.key;
const googleMapKey = sdkConfigs.maps &&
sdkConfigs.maps.google &&
sdkConfigs.maps.google.key;
const aMapKey = sdkConfigs.maps && sdkConfigs.maps.amap && sdkConfigs.maps.amap.key;
const aMapSecurityJsCode = sdkConfigs.maps &&
sdkConfigs.maps.amap &&
sdkConfigs.maps.amap.securityJsCode;
const aMapServiceHost = sdkConfigs.maps &&
sdkConfigs.maps.amap &&
sdkConfigs.maps.amap.serviceHost;
let locale = manifest.locale;
locale = locale && locale.toUpperCase() !== 'AUTO' ? locale : '';
const i18nOptions = (0, uni_cli_shared_1.initI18nOptions)(process.env.UNI_PLATFORM, process.env.UNI_INPUT_DIR, false, false);
const fallbackLocale = (i18nOptions && i18nOptions.locale) || '';
const vueType = process.env.UNI_APP_X === 'true' ? 'uvue' : 'nvue';
const flexDirection = (process.env.UNI_APP_X === 'true'
? manifest['uni-app-x'] && manifest['uni-app-x']['flex-direction']
: manifest['app'] &&
manifest['app'].nvue &&
manifest['app'].nvue['flex-direction']) || 'column';
return {
code: `export const appId = ${JSON.stringify(manifest.appid || '')}
export const appName = ${JSON.stringify(manifest.name || '')}
export const appVersion = ${JSON.stringify(manifest.versionName || '')}
export const appVersionCode = ${JSON.stringify(manifest.versionCode || '')}
export const debug = ${!!debug}
export const ${vueType} = ${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 = ${JSON.stringify(qqMapKey)}
export const bMapKey = ${JSON.stringify(bMapKey)}
export const googleMapKey = ${JSON.stringify(googleMapKey)}
export const aMapKey = ${JSON.stringify(aMapKey)}
export const aMapSecurityJsCode = ${JSON.stringify(aMapSecurityJsCode)}
export const aMapServiceHost = ${JSON.stringify(aMapServiceHost)}
export const sdkConfigs = ${JSON.stringify(sdkConfigs)}
export const locale = '${locale}'
export const fallbackLocale = '${fallbackLocale}'
export const darkmode = ${h5.darkmode || 'false'}
export const themeConfig = ${JSON.stringify((0, uni_cli_shared_1.normalizeThemeConfigOnce)(h5))}
`,
map: { mappings: '' },
};
},
};
});
}
exports.uniManifestJsonPlugin = uniManifestJsonPlugin;
@@ -0,0 +1,3 @@
import type { Plugin } from 'vite';
export declare function getMouseToTouchScript(): string;
export declare function uniMouseToTouchPlugin(): Plugin;
@@ -0,0 +1,85 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniMouseToTouchPlugin = exports.getMouseToTouchScript = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
let script;
function getMouseToTouchScript() {
if (script === undefined) {
const sourcePath = require.resolve('hammer-touchemulator/touch-emulator.js');
const source = fs_1.default.readFileSync(sourcePath, 'utf8');
script = `${source}\n;window.TouchEmulator();`;
}
return script;
}
exports.getMouseToTouchScript = getMouseToTouchScript;
function isEnabled() {
return ((0, uni_cli_shared_1.getPlatformManifestJson)((0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR), 'h5').mouseToTouch === true);
}
function uniMouseToTouchPlugin() {
let config;
let scriptReferenceId;
let getBuildFileName;
function scriptSrc() {
const fileName = getBuildFileName
? getBuildFileName()
: path_1.default.posix.join(config.build.assetsDir, 'touch-emulator.js');
return config.base + fileName;
}
return {
name: 'uni:mouse-to-touch',
configResolved(resolvedConfig) {
config = resolvedConfig;
},
buildStart() {
scriptReferenceId = undefined;
getBuildFileName = undefined;
if (config.command === 'build' && !config.build.ssr && isEnabled()) {
scriptReferenceId = this.emitFile({
type: 'asset',
name: 'touch-emulator.js',
source: getMouseToTouchScript(),
});
}
},
renderStart() {
const referenceId = scriptReferenceId;
if (referenceId) {
getBuildFileName = () => this.getFileName(referenceId);
}
},
configureServer(server) {
const pathname = new URL(scriptSrc(), 'http://localhost').pathname;
server.middlewares.use((req, res, next) => {
if (!isEnabled() ||
(req.method !== 'GET' && req.method !== 'HEAD') ||
req.url?.split('?')[0] !== pathname) {
return next();
}
res.setHeader('Content-Type', 'text/javascript; charset=utf-8');
res.setHeader('Cache-Control', 'no-cache');
res.end(req.method === 'HEAD' ? undefined : getMouseToTouchScript());
});
},
transformIndexHtml: {
order: 'post',
handler() {
if (!isEnabled()) {
return;
}
return [
{
tag: 'script',
attrs: { src: scriptSrc() },
injectTo: 'head-prepend',
},
];
},
},
};
}
exports.uniMouseToTouchPlugin = uniMouseToTouchPlugin;
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniPagesJsonPlugin(): Plugin;
@@ -0,0 +1,319 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniPagesJsonPlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../utils");
function uniPagesJsonPlugin() {
return (0, uni_cli_shared_1.defineUniPagesJsonPlugin)((opts) => {
return {
name: 'uni:h5-pages-json',
enforce: 'pre',
transform(code, id, opt) {
if (opts.filter(id)) {
const { resolvedConfig } = opts;
const ssr = (0, utils_1.isSSR)(opt);
if (process.env.UNI_APP_X === 'true') {
// 调整换行符,确保 parseTree 的loc正确
const jsonCode = code.replace(/\r\n/g, '\n');
(0, uni_cli_shared_1.checkPagesJson)((0, uni_cli_shared_1.preUVueJson)(jsonCode, 'pages.json'), process.env.UNI_INPUT_DIR);
}
return {
code: registerGlobalCode(resolvedConfig, ssr) +
generatePagesJsonCode(ssr, code, resolvedConfig),
map: { mappings: '' },
};
}
},
};
});
}
exports.uniPagesJsonPlugin = uniPagesJsonPlugin;
function generatePagesJsonCode(ssr, jsonStr, config) {
const isWebVapor = (0, uni_cli_shared_1.isUniAppXWebVapor)();
// 标准 Vapor SSR 使用 compiler-ssr,仅客户端使用 Vapor 异步组件包装。
const useVaporAsyncComponent = isWebVapor && !ssr;
const vueImports = useVaporAsyncComponent
? 'defineVaporAsyncComponent as defineAsyncComponent, defineVaporComponent, createAssetComponent'
: 'defineAsyncComponent, resolveComponent, createVNode, withCtx, openBlock, createBlock';
const globalName = getGlobal(ssr);
const pagesJson = (0, uni_cli_shared_1.normalizePagesJson)(jsonStr, process.env.UNI_PLATFORM);
const { importLayoutComponentsCode, defineLayoutComponentsCode } = generateLayoutComponentsCode(globalName, pagesJson);
const definePagesCode = generatePagesDefineCode(pagesJson, config, useVaporAsyncComponent);
const uniRoutesCode = generateRoutes(globalName, pagesJson, config, isWebVapor);
const uniConfigCode = generateConfig(globalName, pagesJson, config);
const cssCode = generateCssCode(config);
const vueType = process.env.UNI_APP_X === 'true' ? 'uvue' : 'nvue';
let workersCode = '';
if (config.command === 'build' && process.env.UNI_APP_X === 'true') {
const workers = (0, uni_cli_shared_1.getWorkers)();
const workerCode = Object.keys(workers).map((key) => {
return `import('@/${key}?worker')`;
});
if (workerCode.length) {
// 仅用于激活动态chunk,运行时不能执行
workersCode = `if(!Math){\n${workerCode.join('\n')}\n}`;
}
}
const pageComponentImport = isWebVapor
? 'createVaporPageRouteComponent'
: 'PageComponent';
return `
import { ${vueImports} } from 'vue'
import { ${pageComponentImport}, useI18n, setupWindow, setupPage } from '@dcloudio/uni-h5'
import { appId, appName, appVersion, appVersionCode, debug, networkTimeout, router, async, sdkConfigs, qqMapKey, googleMapKey, aMapKey, bMapKey, aMapSecurityJsCode, aMapServiceHost, ${vueType}, locale, fallbackLocale, darkmode, themeConfig } from './${uni_cli_shared_1.MANIFEST_JSON_JS}'
const locales = import.meta.glob('./locale/*.json', { eager: true })
${importLayoutComponentsCode}
const extend = Object.assign
${cssCode}
${uniConfigCode}
${defineLayoutComponentsCode}
${definePagesCode}
${uniRoutesCode}
${workersCode}
${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';
}
// 兼容 wx 对象
function registerGlobalCode(config, ssr) {
const name = getGlobal(ssr);
const enableTreeShaking = (0, uni_cli_shared_1.isEnableTreeShaking)((0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR));
if (enableTreeShaking && config.command === 'build' && !ssr) {
// 非 SSR 的发行模式,补充全局 uni 对象
return `import { upx2px, getApp } from '@dcloudio/uni-h5';${name}.uni = {};${name}.wx = {};${name}.rpx2px = upx2px`;
}
return `
import {uni,upx2px,getCurrentPages,getApp,UniServiceJSBridge,UniViewJSBridge} from '@dcloudio/uni-h5'
${name}.getApp = getApp
${name}.getCurrentPages = getCurrentPages
${name}.wx = uni
${name}.uni = uni
${name}.UniViewJSBridge = UniViewJSBridge
${name}.UniServiceJSBridge = UniServiceJSBridge
${name}.rpx2px = upx2px
${name}.__setupPage = (com)=>setupPage(com)
`;
}
function generateCssCode(config) {
const define = config.define;
const cssFiles = [uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'base.css'];
if (config.isProduction) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'shadow.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 ((0, uni_cli_shared_1.isUniAppXWebVapor)()) {
// 导航栏内部直接使用 Loading,发行摇树时也必须保留其样式。
cssFiles.push(uni_cli_shared_1.X_VAPOR_BASE_COMPONENTS_STYLE_PATH + 'loading.css');
}
}
if (define.__UNI_FEATURE_TABBAR__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'tabBar.css');
}
// x 项目按渲染模式加载唯一一份框架基础样式
if (process.env.UNI_APP_X === 'true') {
if ((0, uni_cli_shared_1.isUniAppXWebVapor)()) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'uvue-vapor.css');
}
else {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'uvue.css');
}
}
else {
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((0, uni_cli_shared_1.isUniAppXWebVapor)()
? (0, uni_cli_shared_1.resolveWebVaporComponentStyle)('input')
: uni_cli_shared_1.BASE_COMPONENTS_STYLE_PATH + 'input.css');
}
const enableTreeShaking = (0, uni_cli_shared_1.isEnableTreeShaking)((0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR));
if (config.command === 'serve' || !enableTreeShaking) {
const apiDepsCss = (0, uni_cli_shared_1.API_DEPS_CSS)(process.env.UNI_APP_X === 'true');
// 开发模式或禁用摇树优化,自动添加所有API相关css
Object.keys(apiDepsCss).forEach((name) => {
const styles = apiDepsCss[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: -1,
leftWindow: -2,
rightWindow: -3,
};
let importLayoutComponentsCode = '';
let defineLayoutComponentsCode = `${globalName}.__uniLayout = ${globalName}.__uniLayout || {}\n`;
Object.keys(windowNames).forEach((name) => {
const windowConfig = pagesJson[name];
if (windowConfig && windowConfig.path) {
importLayoutComponentsCode += `const ${name} = defineAsyncComponent(()=>import('./${windowConfig.path}').then(com=>setupWindow(com.default || com,${windowNames[name]})))\n`;
defineLayoutComponentsCode += `${globalName}.__uniConfig.${name}.component = ${name}\n`;
}
});
return {
importLayoutComponentsCode,
defineLayoutComponentsCode,
};
}
function generatePageDefineCode(pageOptions) {
let pagePathWithExtname = (0, uni_cli_shared_1.normalizePagePath)(pageOptions.path, 'h5');
if (!pagePathWithExtname) {
// 不存在时,仍引用,此时编译会报错文件不存在
pagePathWithExtname = pageOptions.path + '.vue';
}
const pageIdent = (0, uni_cli_shared_1.normalizeIdentifier)(pageOptions.path);
return `const ${pageIdent}Loader = ()=>import('./${pagePathWithExtname}').then(com => setupPage(com.default || com, '${pagePathWithExtname}'))
const ${pageIdent} = defineAsyncComponent(extend({loader:${pageIdent}Loader},AsyncComponentOptions))`;
}
function generatePagesDefineCode(pagesJson, _config, useVaporAsyncComponent) {
const { pages } = pagesJson;
const asyncFallbackComponentsCode = useVaporAsyncComponent
? `if(async.loading){
AsyncComponentOptions.loadingComponent = defineVaporComponent({
name:'SystemAsyncLoading',
setup(){
return createAssetComponent(async.loading, null, null, true)
}
})
}
if(async.error){
AsyncComponentOptions.errorComponent = defineVaporComponent({
name:'SystemAsyncError',
props:['error'],
setup(props){
return createAssetComponent(async.error, { error: () => props.error }, null, true)
}
})
}`
: `if(async.loading){
AsyncComponentOptions.loadingComponent = {
name:'SystemAsyncLoading',
render(){
return createVNode(resolveComponent(async.loading))
}
}
}
if(async.error){
AsyncComponentOptions.errorComponent = {
name:'SystemAsyncError',
props:['error'],
render(){
return createVNode(resolveComponent(async.error), { error: this.error })
}
}
}`;
return (`const AsyncComponentOptions = {
delay: async.delay,
timeout: async.timeout,
suspensible: async.suspensible
}
${asyncFallbackComponentsCode}
` + pages.map((pageOptions) => generatePageDefineCode(pageOptions)).join('\n'));
}
function generatePageRoute({ path, meta }, _config, isWebVapor) {
const { isEntry } = meta;
const alias = isEntry ? `\n alias:'/${path}',` : '';
const pageComponent = (0, uni_cli_shared_1.normalizeIdentifier)(path);
if (isWebVapor) {
return `{
path:'/${isEntry ? '' : path}',${alias}
component:createVaporPageRouteComponent(${pageComponent}),
loader: ${pageComponent}Loader,
meta: ${JSON.stringify(meta)}
}`;
}
// 目前单页面未处理 query=>props
const queryCode = process.env.UNI_APP_X === 'true'
? 'app && app.vm && app.vm.$route && app.vm.$route.query || {};'
: 'app && app.$route && app.$route.query || {};';
return `{
path:'/${isEntry ? '' : path}',${alias}
component:{setup(){ const app = getApp(); const query = ${queryCode} return ()=>renderPage(${pageComponent},query)}},
loader: ${pageComponent}Loader,
meta: ${JSON.stringify(meta)}
}`;
}
function generatePagesRoute(pagesRouteOptions, config, isWebVapor) {
return pagesRouteOptions.map((pageOptions) => generatePageRoute(pageOptions, config, isWebVapor));
}
function generateRoutes(globalName, pagesJson, config, isWebVapor) {
const routesCode = [
...generatePagesRoute((0, uni_cli_shared_1.normalizePagesRoute)(pagesJson), config, isWebVapor),
].join(',');
if (isWebVapor) {
return `
${globalName}.__uniRoutes=[${routesCode}].map(uniRoute=>(uniRoute.meta.route = (uniRoute.alias || uniRoute.path).slice(1),uniRoute))`;
}
return `
function renderPage(component,props){
return (openBlock(), createBlock(PageComponent, null, {page: withCtx(() => [createVNode(component, extend({},props,{ref: "page"}), null, 512 /* NEED_PATCH */)]), _: 1 /* STABLE */}))
}
${globalName}.__uniRoutes=[${routesCode}].map(uniRoute=>(uniRoute.meta.route = (uniRoute.alias || uniRoute.path).slice(1),uniRoute))`;
}
function generateConfig(globalName, pagesJson, config) {
const isX = process.env.UNI_APP_X === 'true';
delete pagesJson.pages;
delete pagesJson.subPackages;
delete pagesJson.subpackages;
pagesJson.compilerVersion = process.env.UNI_COMPILER_VERSION;
const vueType = isX ? 'uvue' : 'nvue';
let tabBarCode = '';
if (isX) {
const tabBar = pagesJson.tabBar;
delete pagesJson.tabBar;
tabBarCode = `${globalName}.__uniConfig.getTabBarConfig = () => {return ${tabBar ? JSON.stringify(tabBar) : 'undefined'}};
${globalName}.__uniConfig.tabBar = __uniConfig.getTabBarConfig();`;
}
return `${isX ? `${globalName}.__uniX = true` : ''}
${globalName}.__uniConfig=extend(${JSON.stringify(pagesJson)},{
appId,
appName,
appVersion,
appVersionCode,
async,
debug,
networkTimeout,
sdkConfigs,
qqMapKey,
bMapKey,
googleMapKey,
aMapKey,
aMapSecurityJsCode,
aMapServiceHost,
${vueType},
locale,
fallbackLocale,
locales:Object.keys(locales).reduce((res,name)=>{const locale=name.replace(/\\.\\/locale\\/(uni-app.)?(.*).json/,'$2');extend(res[locale]||(res[locale]={}),locales[name].default);return res},{}),
router,
darkmode,
themeConfig,
})
${tabBarCode}
`;
}
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniPostVuePlugin(): Plugin;
@@ -0,0 +1,48 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniPostVuePlugin = void 0;
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const WXS_RE = /vue&type=(wxs|renderjs)/;
function uniPostVuePlugin() {
return {
name: 'uni:post-vue',
apply: 'serve',
enforce: 'post',
async transform(code, id) {
const { filename, query } = (0, uni_cli_shared_1.parseVueRequest)(id);
if (query.vue) {
return;
}
if (!uni_cli_shared_1.EXTNAME_VUE.includes(path_1.default.extname(filename))) {
return;
}
if (!WXS_RE.test(code)) {
return;
}
const hmrId = parseHmrId(code);
if (!hmrId) {
return;
}
// TODO 内部解决 @vitejs/plugin-vue 自定义块外链热刷的问题
// https://github.com/vitejs/vite/blob/main/packages/plugin-vue/src/main.ts#L387
// 没有增加 src=descriptor.id
// 包含外链 wxs,renderjs
code = code.replace(/vue&type=(wxs|renderjs)&index=([0-9]+)&src&/gi, (_, type, index) => {
return `vue&type=${type}&index=${index}&src=${hmrId}&`;
});
return {
code: code, // 暂不提供sourcemap,意义不大
map: null,
};
},
};
}
exports.uniPostVuePlugin = uniPostVuePlugin;
function parseHmrId(code) {
const matches = code.match(/_sfc_main.__hmrId = "(.*)"/);
return matches && matches[1];
}
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniRenderjsPlugin(): Plugin;
@@ -0,0 +1,47 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniRenderjsPlugin = void 0;
const debug_1 = __importDefault(require("debug"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const debugRenderjs = (0, debug_1.default)('uni:h5-renderjs');
function uniRenderjsPlugin() {
return {
name: 'uni:h5-renderjs',
transform(code, id) {
const { type, name } = (0, uni_cli_shared_1.parseRenderjs)(id);
if (!type) {
return;
}
debugRenderjs(id);
if (!name) {
this.error((0, uni_cli_shared_1.missingModuleName)(type, code));
}
return {
code: `${require('@vue/compiler-sfc').rewriteDefault(code.replace(/module\.exports\s*=/, 'export default '), '_sfc_' + type)}
${type === 'renderjs' ? genRenderjsCode(name) : genWxsCode(name)}`,
map: { mappings: '' },
};
},
};
}
exports.uniRenderjsPlugin = uniRenderjsPlugin;
function genRenderjsCode(name) {
return `export default Comp => {
if(!Comp.$renderjs){Comp.$renderjs = []}
Comp.$renderjs.push('${name}')
if(!Comp.mixins){Comp.mixins = []}
Comp.mixins.push({beforeCreate(){ this['${name}'] = this },mounted(){ this.$ownerInstance = this.$gcd(this, true) }})
Comp.mixins.push(_sfc_renderjs)
}`;
}
function genWxsCode(name) {
return `export default Comp => {
if(!Comp.$wxs){Comp.$wxs = []}
Comp.$wxs.push('${name}')
if(!Comp.mixins){Comp.mixins = []}
Comp.mixins.push({beforeCreate(){ this['${name}'] = _sfc_wxs }})
}`;
}
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniResolveIdPlugin(): Plugin;
@@ -0,0 +1,57 @@
"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 utils_1 = require("../utils");
const debugResolve = (0, debug_1.default)('uni:resolve');
function uniResolveIdPlugin() {
const resolveCache = {};
const mainPath = (0, uni_cli_shared_1.resolveMainPathOnce)(process.env.UNI_INPUT_DIR);
return {
name: 'uni:h5-resolve-id',
enforce: 'pre',
configResolved(config) {
resolveCache[utils_1.ownerModuleName] = (0, uni_cli_shared_1.resolveBuiltIn)(path_1.default.posix.join(utils_1.ownerModuleName, (0, utils_1.resolveFrameworkDistDir)() + '/uni-h5.es.js'));
resolveCache['@dcloudio/uni-h5-vue'] = (0, uni_cli_shared_1.resolveBuiltIn)(path_1.default.posix.join('@dcloudio/uni-h5-vue', (0, utils_1.resolveVueDistDir)() +
`/vue.runtime.${process.env.VITEST ? 'cjs' : 'esm'}.js`));
},
resolveId(id, importer, options) {
if (id === '/main' && importer && importer.endsWith('index.html')) {
return mainPath;
}
if (id === 'vue') {
id = '@dcloudio/uni-h5-vue';
}
if ((0, utils_1.isSSR)(options)) {
if (id === utils_1.ownerModuleName) {
if ((0, uni_cli_shared_1.isUniAppXWebVapor)()) {
return (0, uni_cli_shared_1.resolveBuiltIn)(path_1.default.posix.join(utils_1.ownerModuleName, 'dist-x-vapor-ssr/uni-h5.es.js'));
}
}
if (id === '@dcloudio/uni-h5-vue') {
const runtimeFile = (0, uni_cli_shared_1.isUniAppXWebVapor)()
? 'vue.runtime.esm.js'
: 'vue.runtime.cjs.js';
return (0, uni_cli_shared_1.resolveBuiltIn)(path_1.default.posix.join('@dcloudio/uni-h5-vue', (0, utils_1.resolveVueDistDir)(), runtimeFile));
}
}
const cache = resolveCache[id];
if (cache) {
debugResolve('cache', id, cache);
return cache;
}
if (id.startsWith('@dcloudio/uni-h5/style')) {
return (resolveCache[id] = (0, uni_cli_shared_1.resolveBuiltIn)(id));
}
if (id.startsWith('@dcloudio/uni-components/style')) {
return (resolveCache[id] = (0, uni_cli_shared_1.resolveBuiltIn)(id));
}
},
};
}
exports.uniResolveIdPlugin = uniResolveIdPlugin;
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniSetupPlugin(): Plugin;
+34
View File
@@ -0,0 +1,34 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniSetupPlugin = void 0;
const debug_1 = __importDefault(require("debug"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const debugSetup = (0, debug_1.default)('uni:setup');
function uniSetupPlugin() {
let appVuePath;
let resolvedConfig;
return {
name: 'uni:setup',
configResolved(config) {
resolvedConfig = config;
appVuePath = (0, uni_cli_shared_1.resolveAppVue)(process.env.UNI_INPUT_DIR);
},
transform(code, id) {
const { filename, query } = (0, uni_cli_shared_1.parseVueRequest)(id);
if (filename === appVuePath && !query.vue) {
debugSetup(filename);
return {
code: code +
`;import { setupApp } from '@dcloudio/uni-h5';setupApp(_sfc_main);`,
map: (0, uni_cli_shared_1.withSourcemap)(resolvedConfig)
? this.getCombinedSourcemap()
: null,
};
}
},
};
}
exports.uniSetupPlugin = uniSetupPlugin;
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniPostSourceMapPlugin(): Plugin;
@@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniPostSourceMapPlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const path_1 = require("path");
function uniPostSourceMapPlugin() {
return {
name: 'uni:post-sourcemap',
apply: 'serve',
enforce: 'post',
configureServer(server) {
// cli 工程呢?
// 重要:hack 了 _pendingRequests,来修改 map
const pendingRequests = new PendingRequests();
pendingRequests._server = server;
pendingRequests._inputDir = (0, uni_cli_shared_1.normalizePath)(process.env.UNI_INPUT_DIR);
// @ts-expect-error
server._pendingRequests = pendingRequests;
},
};
}
exports.uniPostSourceMapPlugin = uniPostSourceMapPlugin;
function isSourceMap(map) {
return map && map.sources;
}
class PendingRequests extends Map {
set(key, value) {
const then = value.request.then;
// @ts-expect-error
value.request.then = (onFulfilled, onRejected) => {
// @ts-expect-error
return then.call(value.request, (request) => {
const map = request?.map;
if (map) {
// @ts-expect-error
const mod = this._server.moduleGraph._getUnresolvedUrlToModule(key);
if (mod && mod.file && (0, path_1.isAbsolute)(mod.file)) {
const dir = (0, uni_cli_shared_1.normalizePath)((0, path_1.dirname)(mod.file));
if (dir.startsWith(this._inputDir) && isSourceMap(map)) {
for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
const sourcePath = map.sources[sourcesIndex];
if (sourcePath) {
// 将相对路径转换为绝对路径
if (!(0, path_1.isAbsolute)(sourcePath)) {
map.sources[sourcesIndex] = (0, uni_cli_shared_1.normalizePath)((0, path_1.join)(dir, sourcePath));
}
}
}
}
}
}
return onFulfilled?.(request);
}, onRejected);
};
return super.set(key, value);
}
}
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniSSRPlugin(): Plugin;
+87
View File
@@ -0,0 +1,87 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniSSRPlugin = void 0;
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../utils");
const ENTRY_SERVER_JS = 'entry-server.js';
function uniSSRPlugin() {
let entryServerJs;
let resolvedConfig;
const entryServerJsCode = (0, utils_1.generateSsrEntryServerCode)();
return {
name: 'uni:h5-ssr',
config(userConfig, env) {
if ((0, uni_cli_shared_1.isSsr)(env.command, userConfig)) {
(0, utils_1.initSsrAliasOnce)();
(0, utils_1.rewriteSsrVue)();
if (!(0, uni_cli_shared_1.isUniAppXWebVapor)()) {
(0, utils_1.rewriteSsrNativeTag)();
}
(0, utils_1.rewriteSsrRenderStyle)(process.env.UNI_INPUT_DIR);
const alias = [
{
find: 'vue/server-renderer',
replacement: path_1.default.dirname((0, uni_cli_shared_1.resolveBuiltIn)('@vue/server-renderer')),
},
];
if ((0, uni_cli_shared_1.isUniAppXWebVapor)()) {
// TODO: Web Vapor SSR 需让 ESM renderer 接入现有的动态样式 rpx 转换。
alias.push({
find: '@vue/server-renderer',
replacement: (0, uni_cli_shared_1.resolveWebVaporPackage)('@vue/server-renderer/dist/server-renderer.esm-bundler.js'),
}, {
find: '@vue/runtime-dom',
replacement: (0, uni_cli_shared_1.resolveBuiltIn)(`@dcloudio/uni-h5-vue/${(0, utils_1.resolveVueDistDir)()}/vue.runtime.esm.js`),
}, {
find: '@vue/shared',
replacement: (0, uni_cli_shared_1.resolveWebVaporPackage)('@vue/shared/dist/shared.esm-bundler.js'),
});
}
try {
const replacement = path_1.default.dirname((0, uni_cli_shared_1.resolveBuiltIn)('vuex/package.json'));
alias.push({
find: 'vuex',
replacement,
});
}
catch (error) { }
return {
resolve: {
alias,
},
};
}
},
configResolved(config) {
resolvedConfig = config;
entryServerJs = path_1.default.join(process.env.UNI_INPUT_DIR, ENTRY_SERVER_JS);
if ((0, uni_cli_shared_1.isSsr)(resolvedConfig.command, resolvedConfig)) {
(0, utils_1.initSsrDefine)(resolvedConfig);
}
},
resolveId(id) {
if (id.endsWith(ENTRY_SERVER_JS)) {
return entryServerJs;
}
},
load(id) {
if (id.endsWith(ENTRY_SERVER_JS)) {
return entryServerJsCode;
}
},
generateBundle(_options, bundle) {
const chunk = bundle['entry-server.js'];
if (chunk) {
chunk.code =
(0, utils_1.generateSsrDefineCode)(resolvedConfig, (0, uni_cli_shared_1.parseRpx2UnitOnce)(process.env.UNI_INPUT_DIR, process.env.UNI_PLATFORM)) +
'\n' +
chunk.code;
}
},
};
}
exports.uniSSRPlugin = uniSSRPlugin;
@@ -0,0 +1,2 @@
export declare const ownerModuleName = "@dcloudio/uni-h5";
export declare const AliYunCloudAuthWebSDK = "https://cn-shanghai-aliyun-cloudauth.oss-cn-shanghai.aliyuncs.com/web_sdk_js/jsvm_all.js";
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AliYunCloudAuthWebSDK = exports.ownerModuleName = void 0;
exports.ownerModuleName = '@dcloudio/uni-h5';
exports.AliYunCloudAuthWebSDK = 'https://cn-shanghai-aliyun-cloudauth.oss-cn-shanghai.aliyuncs.com/web_sdk_js/jsvm_all.js';
@@ -0,0 +1,2 @@
import type { ConfigEnv, UserConfig } from 'vite';
export declare function createDefine(command: ConfigEnv['command'], config: UserConfig): UserConfig['define'];
+18
View File
@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDefine = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const ssr_1 = require("./ssr");
function createDefine(command, config) {
const platform = process.env.UNI_PLATFORM;
const inputDir = process.env.UNI_INPUT_DIR;
return (0, uni_cli_shared_1.initFeatures)({
inputDir,
command,
platform,
pagesJson: (0, uni_cli_shared_1.parsePagesJsonOnce)(inputDir, platform),
manifestJson: (0, uni_cli_shared_1.parseManifestJsonOnce)(inputDir),
ssr: (0, uni_cli_shared_1.isSsr)(command, config) || (0, ssr_1.isSsrManifest)(command, config),
});
}
exports.createDefine = createDefine;
@@ -0,0 +1,4 @@
export * from './ssr';
export * from './features';
export * from './constants';
export * from './utils';
+20
View File
@@ -0,0 +1,20 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./ssr"), exports);
__exportStar(require("./features"), exports);
__exportStar(require("./constants"), exports);
__exportStar(require("./utils"), exports);
@@ -0,0 +1,5 @@
/**
* 重写 @vue/compiler-sfc 的 parse 函数
* web 平台下,如果 SFC 没有 style,注入一个默认的空 style
*/
export declare function rewriteCompilerSfcParse(): void;
+21
View File
@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.rewriteCompilerSfcParse = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
/**
* 重写 @vue/compiler-sfc 的 parse 函数
* web 平台下,如果 SFC 没有 style,注入一个默认的空 style
*/
function rewriteCompilerSfcParse() {
const compilerSfc = require((0, uni_cli_shared_1.resolveBuiltIn)('@vue/compiler-sfc'));
const { parse } = compilerSfc;
compilerSfc.parse = (source, options) => {
const result = parse(source, options);
// 如果没有 style,注入一个默认的空 style
if (result.descriptor.styles.length === 0) {
result.descriptor.styles = [(0, uni_cli_shared_1.createDefaultSFCStyleBlock)(source)];
}
return result;
};
}
exports.rewriteCompilerSfcParse = rewriteCompilerSfcParse;
+16
View File
@@ -0,0 +1,16 @@
import { type Rpx2UnitOptions } from '@dcloudio/uni-shared';
import type { ConfigEnv, ResolvedConfig, UserConfig } from 'vite';
export declare const isSSR: (opt: {
ssr?: boolean;
} | boolean | undefined) => boolean;
export declare function isSsrManifest(command: ConfigEnv['command'], config: UserConfig | ResolvedConfig): boolean;
export declare const initSsrAliasOnce: () => void;
export declare function initSsrDefine(config: ResolvedConfig): typeof globalThis & {
__IMPORT_META_ENV_BASE_URL__: any;
};
export declare function generateSsrDefineCode(config: ResolvedConfig, { unit, unitRatio, unitPrecision }: Rpx2UnitOptions): string;
export declare function generateSsrEntryServerCode(): string;
export declare function rewriteSsrVue(): void;
export declare function rewriteSsrResolve(): void;
export declare function rewriteSsrNativeTag(): void;
export declare function rewriteSsrRenderStyle(inputDir: string): void;
+205
View File
@@ -0,0 +1,205 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.rewriteSsrRenderStyle = exports.rewriteSsrNativeTag = exports.rewriteSsrResolve = exports.rewriteSsrVue = exports.generateSsrEntryServerCode = exports.generateSsrDefineCode = exports.initSsrDefine = exports.initSsrAliasOnce = exports.isSsrManifest = exports.isSSR = void 0;
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const shared_1 = require("@vue/shared");
const uni_shared_1 = require("@dcloudio/uni-shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const transformPageHead_1 = require("../plugin/transforms/transformPageHead");
const utils_1 = require("./utils");
// Temporal handling for 2.7 breaking change
const isSSR = (opt) => opt === undefined ? false : typeof opt === 'boolean' ? opt : opt?.ssr === true;
exports.isSSR = isSSR;
function isSsrManifest(command, config) {
if (command === 'build') {
return !!(config.build && config.build.ssrManifest);
}
return false;
}
exports.isSsrManifest = isSsrManifest;
const SSR_ALIAS = {
vue: '@dcloudio/uni-h5-vue',
'vue/server-renderer': 'vue/server-renderer',
'@vue/server-renderer': '@vue/server-renderer',
'@dcloudio/uni-cloud': '@dcloudio/uni-cloud',
'@dcloudio/uni-h5': '@dcloudio/uni-h5',
'@dcloudio/uni-app': '@dcloudio/uni-app',
'@dcloudio/uni-i18n': '@dcloudio/uni-i18n',
'@dcloudio/uni-shared': '@dcloudio/uni-shared',
};
const SSR_DIST_X_ALIAS_KEY = ['uni-h5-vue', 'uni-h5'];
exports.initSsrAliasOnce = (0, uni_shared_1.once)(() => {
// 重写 package.json 的读取
const oldJoin = path_1.default.join;
const oldReadFileSync = fs_1.default.readFileSync;
const alias = Object.keys(SSR_ALIAS).reduce((alias, key) => {
const newKey = oldJoin('node_modules', key, 'package.json');
if (key.endsWith('vue/server-renderer')) {
alias[newKey] = path_1.default.join(path_1.default.dirname((0, uni_cli_shared_1.resolveBuiltIn)(SSR_ALIAS[key])), 'package.json');
}
else {
alias[newKey] = (0, uni_cli_shared_1.resolveBuiltIn)(SSR_ALIAS[key] + '/package.json');
}
return alias;
}, {});
// console.log(alias)
path_1.default.join = (...paths) => {
let res = oldJoin.apply(path_1.default, paths);
if (res.endsWith('package.json')) {
const key = Object.keys(alias).find((key) => res.endsWith(key));
if (key) {
res = alias[key];
}
}
return res;
};
if (process.env.UNI_APP_X === 'true') {
// @ts-expect-error
fs_1.default.readFileSync = (...args) => {
// @ts-expect-error
const res = oldReadFileSync.apply(fs_1.default, args);
if (!(args.length === 2 &&
typeof args[0] === 'string' &&
(args[1] === 'utf-8' || args[1] === 'utf8'))) {
return res;
}
const path = (0, uni_cli_shared_1.normalizePath)(args[0]);
const shouldRedirectToDistX = SSR_DIST_X_ALIAS_KEY.some((key) => path.endsWith(key + '/package.json'));
if (shouldRedirectToDistX) {
const pkgData = JSON.parse(res);
const distDir = (0, utils_1.resolveDistDir)() + '/';
if (pkgData.module) {
pkgData.module = pkgData.module.replace(/dist\//, distDir);
}
if (pkgData.main) {
pkgData.main = pkgData.main.replace(/dist\//, distDir);
}
return JSON.stringify(pkgData, null, 2);
}
return res;
};
}
});
function initSsrDefine(config) {
return (0, shared_1.extend)(globalThis, {
__IMPORT_META_ENV_BASE_URL__: config.env.BASE_URL,
});
}
exports.initSsrDefine = initSsrDefine;
function serializeDefine(define) {
let res = `{`;
for (const key in define) {
const val = define[key];
res += `${JSON.stringify(key)}: ${(0, shared_1.isString)(val) ? `(${val})` : JSON.stringify(val)}, `;
}
return res + `}`;
}
function normalizeSsrDefine(config) {
const defines = (0, shared_1.extend)({
__IMPORT_META_ENV_BASE_URL__: JSON.stringify(config.env.BASE_URL),
}, config.define);
delete defines['import.meta.env.LEGACY'];
return defines;
}
function generateSsrDefineCode(config, { unit, unitRatio, unitPrecision }) {
return fs_1.default
.readFileSync(path_1.default.join(__dirname, '../../lib/ssr/define.js'), 'utf8')
.replace('__DEFINES__', serializeDefine(normalizeSsrDefine(config)))
.replace('__UNIT__', JSON.stringify(unit))
.replace('__UNIT_RATIO__', JSON.stringify(unitRatio))
.replace('__UNIT_PRECISION__', JSON.stringify(unitPrecision));
}
exports.generateSsrDefineCode = generateSsrDefineCode;
function generateSsrEntryServerCode() {
return fs_1.default.readFileSync(path_1.default.join(__dirname, '../../lib/ssr/entry-server.js'), 'utf8');
}
exports.generateSsrEntryServerCode = generateSsrEntryServerCode;
function rewriteSsrVue() {
// 解决 @vue/server-renderer 中引入 vue 的映射
const vueRuntime = (0, uni_cli_shared_1.resolveBuiltIn)('@dcloudio/uni-h5-vue/' + (0, utils_1.resolveVueDistDir)() + '/vue.runtime.cjs.js');
const aliases = {
vue: vueRuntime,
'vue/package.json': (0, uni_cli_shared_1.resolveBuiltIn)('@dcloudio/uni-h5-vue/package.json'),
};
if ((0, uni_cli_shared_1.isUniAppXWebVapor)()) {
// Web Vapor server-renderer 使用同一份 Vapor runtime-dom。
aliases['@vue/runtime-dom'] = vueRuntime;
}
require('module-alias').addAliases(aliases);
// TODO vite 2.7.0 版本会定制 require 的解析,解析后缓存的文件路径会被格式化,导致 windows 平台路径不一致,导致 cache 不生效
if (require('os').platform() === 'win32') {
require('vue');
const vuePath = require.resolve('vue');
require.cache[(0, uni_cli_shared_1.normalizePath)(vuePath)] = require.cache[vuePath];
}
}
exports.rewriteSsrVue = rewriteSsrVue;
function initResolveSyncOpts(opts) {
if (!opts) {
opts = {};
}
if (!opts.paths) {
opts.paths = [];
}
if ((0, shared_1.isString)(opts.paths)) {
opts.paths = [opts.paths];
}
if ((0, shared_1.isArray)(opts.paths)) {
opts.paths.push(...(0, uni_cli_shared_1.getBuiltInPaths)());
}
return opts;
}
function rewriteSsrResolve() {
// 解决 ssr 时 __vite_ssr_import__("vue") 的映射
const resolve = require(require.resolve('resolve', {
paths: [
path_1.default.resolve(require.resolve('vite/package.json'), '../node_modules'),
],
}));
const oldSync = resolve.sync;
resolve.sync = (id, opts) => {
if (id === 'vue') {
return (0, uni_cli_shared_1.resolveBuiltIn)('@dcloudio/uni-h5-vue/' + (0, utils_1.resolveVueDistDir)() + '/vue.runtime.cjs.js');
}
else if (id === 'vue/package.json') {
return (0, uni_cli_shared_1.resolveBuiltIn)(`@dcloudio/uni-h5-vue/package.json`);
}
else if (id === 'vue/server-renderer/package.json') {
return (0, uni_cli_shared_1.resolveBuiltIn)(`@vue/server-renderer/package.json`);
}
return oldSync(id, initResolveSyncOpts(opts));
};
}
exports.rewriteSsrResolve = rewriteSsrResolve;
function rewriteSsrNativeTag() {
const compilerDom = require((0, uni_cli_shared_1.resolveBuiltIn)('@vue/compiler-dom'));
// TODO compiler-ssr时,传入的 isNativeTag 会被 @vue/compiler-dom 的 isNativeTag 覆盖
// https://github.com/vuejs/vue-next/blob/master/packages/compiler-ssr/src/index.ts#L36
compilerDom.parserOptions.isNativeTag = uni_shared_1.isH5NativeTag;
// ssr 时,ssrTransformComponent 执行时机很早,导致无法正确重写 tag,故通过 resolveComponentType 解决重写
const oldResolveComponentType = compilerDom.resolveComponentType;
const newResolveComponentType = function (node, context, ssr) {
(0, transformPageHead_1.transformPageHead)(node, context);
(0, uni_cli_shared_1.transformMatchMedia)(node, context);
(0, uni_cli_shared_1.transformH5BuiltInComponents)(node, context);
return oldResolveComponentType(node, context, ssr);
};
compilerDom.resolveComponentType = newResolveComponentType;
}
exports.rewriteSsrNativeTag = rewriteSsrNativeTag;
function rewriteSsrRenderStyle(inputDir) {
const { unit, unitRatio, unitPrecision } = (0, uni_cli_shared_1.parseRpx2UnitOnce)(inputDir, 'h5');
const rpx2unit = (0, uni_shared_1.createRpx2Unit)(unit, unitRatio, unitPrecision);
const shared = require('@vue/shared');
const oldStringifyStyle = shared.stringifyStyle;
shared.stringifyStyle = (styles) => rpx2unit(oldStringifyStyle(styles));
const serverRender = require('@vue/server-renderer');
const oldSsrRenderStyle = serverRender.ssrRenderStyle;
// 仅对字符串类型做转换,非字符串类型,通过 stringifyStyle 转换
serverRender.ssrRenderStyle = (raw) => (0, shared_1.isString)(raw) ? rpx2unit(oldSsrRenderStyle(raw)) : oldSsrRenderStyle(raw);
}
exports.rewriteSsrRenderStyle = rewriteSsrRenderStyle;
@@ -0,0 +1,3 @@
export declare function resolveFrameworkDistDir(): "dist-x-vapor" | "dist-x" | "dist";
export declare function resolveVueDistDir(): "dist-x-vapor" | "dist-x" | "dist";
export declare function resolveDistDir(): "dist-x-vapor" | "dist-x" | "dist";
+20
View File
@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveDistDir = exports.resolveVueDistDir = exports.resolveFrameworkDistDir = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function resolveFrameworkDistDir() {
return resolveDistDir();
}
exports.resolveFrameworkDistDir = resolveFrameworkDistDir;
function resolveVueDistDir() {
return resolveDistDir();
}
exports.resolveVueDistDir = resolveVueDistDir;
function resolveDistDir() {
return (0, uni_cli_shared_1.isUniAppXWebVapor)()
? 'dist-x-vapor'
: process.env.UNI_APP_X === 'true'
? 'dist-x'
: 'dist';
}
exports.resolveDistDir = resolveDistDir;
+182
View File
@@ -0,0 +1,182 @@
[
"$emit",
"$off",
"$on",
"$once",
"__f__",
"addInterceptor",
"addPhoneContact",
"arrayBufferToBase64",
"base64ToArrayBuffer",
"canIUse",
"canvasGetImageData",
"canvasPutImageData",
"canvasToTempFilePath",
"chooseFile",
"chooseImage",
"chooseLocation",
"chooseVideo",
"clearStorage",
"clearStorageSync",
"closePreviewImage",
"closeSocket",
"connectSocket",
"createAnimation",
"createCameraContext",
"createCanvasContext",
"createInnerAudioContext",
"createIntersectionObserver",
"createLivePlayerContext",
"createMapContext",
"createMediaQueryObserver",
"createSelectorQuery",
"createVideoContext",
"downloadFile",
"getAppBaseInfo",
"getClipboardData",
"getDeviceInfo",
"getEnterOptionsSync",
"getFacialRecognitionMetaInfo",
"getFileInfo",
"getImageInfo",
"getLaunchOptionsSync",
"getLeftWindowStyle",
"getLocale",
"getLocation",
"getNetworkType",
"getProvider",
"getPushClientId",
"getRealPath",
"getRecorderManager",
"getRightWindowStyle",
"getSavedFileInfo",
"getSavedFileList",
"getScreenBrightness",
"getSelectedTextRange",
"getStorage",
"getStorageInfo",
"getStorageInfoSync",
"getStorageSync",
"getSystemInfo",
"getSystemInfoSync",
"getTabBarPageId",
"getTopWindowStyle",
"getVideoInfo",
"getWindowInfo",
"hideActionSheet",
"hideKeyboard",
"hideLeftWindow",
"hideLoading",
"hideModal",
"hideNavigationBarLoading",
"hideRightWindow",
"hideTabBar",
"hideTabBarRedDot",
"hideToast",
"hideTopWindow",
"interceptors",
"invokePushCallback",
"loadFontFace",
"login",
"makePhoneCall",
"navigateBack",
"navigateTo",
"offAccelerometerChange",
"offAppHide",
"offAppShow",
"offCompassChange",
"offError",
"offLocationChange",
"offLocationChangeError",
"offNetworkStatusChange",
"offPageNotFound",
"offPushMessage",
"offThemeChange",
"offUnhandledRejection",
"offWindowResize",
"onAccelerometerChange",
"onAppHide",
"onAppShow",
"onCompassChange",
"onCreateVueApp",
"onError",
"onGyroscopeChange",
"onLocaleChange",
"onLocationChange",
"onLocationChangeError",
"onMemoryWarning",
"onNetworkStatusChange",
"onPageNotFound",
"onPushMessage",
"onSocketClose",
"onSocketError",
"onSocketMessage",
"onSocketOpen",
"onTabBarMidButtonTap",
"onThemeChange",
"onUnhandledRejection",
"onUserCaptureScreen",
"onWindowResize",
"openDocument",
"openLocation",
"pageScrollTo",
"preloadPage",
"previewImage",
"reLaunch",
"redirectTo",
"removeAllPages",
"removeInterceptor",
"removeLastPage",
"removeNonTabBarPages",
"removeSavedFile",
"removeStorage",
"removeStorageSync",
"removeTabBarBadge",
"request",
"rpx2px",
"saveFile",
"saveImageToPhotosAlbum",
"saveVideoToPhotosAlbum",
"scanCode",
"sendSocketMessage",
"setClipboardData",
"setKeepScreenOn",
"setLeftWindowStyle",
"setLocale",
"setNavigationBarColor",
"setNavigationBarTitle",
"setPageMeta",
"setRightWindowStyle",
"setScreenBrightness",
"setStorage",
"setStorageSync",
"setTabBarBadge",
"setTabBarItem",
"setTabBarStyle",
"setTopWindowStyle",
"showActionSheet",
"showLeftWindow",
"showLoading",
"showModal",
"showNavigationBarLoading",
"showRightWindow",
"showTabBar",
"showTabBarRedDot",
"showToast",
"showTopWindow",
"startAccelerometer",
"startCompass",
"startGyroscope",
"startLocationUpdate",
"startPullDownRefresh",
"stopAccelerometer",
"stopCompass",
"stopGyroscope",
"stopLocationUpdate",
"stopPullDownRefresh",
"switchTab",
"uploadFile",
"upx2px",
"vibrateLong",
"vibrateShort"
]
+200
View File
@@ -0,0 +1,200 @@
[
"$emit",
"$off",
"$on",
"$once",
"UTS",
"UTSJSONObject",
"UTSValueIterable",
"UniError",
"__f__",
"addInterceptor",
"addPhoneContact",
"arrayBufferToBase64",
"base64ToArrayBuffer",
"canIUse",
"canvasGetImageData",
"canvasPutImageData",
"canvasToTempFilePath",
"chooseFile",
"chooseImage",
"chooseLocation",
"chooseVideo",
"clearStorage",
"clearStorageSync",
"closeDialogPage",
"closePreviewImage",
"closeSocket",
"connectSocket",
"createAnimation",
"createCameraContext",
"createCanvasContext",
"createCanvasContextAsync",
"createEditorContextAsync",
"createInnerAudioContext",
"createIntersectionObserver",
"createLivePlayerContext",
"createMapContext",
"createMediaQueryObserver",
"createSelectorQuery",
"createVideoContext",
"createWorker",
"downloadFile",
"getAppBaseInfo",
"getClipboardData",
"getDeviceInfo",
"getElementById",
"getEnterOptionsSync",
"getFacialRecognitionMetaInfo",
"getFileInfo",
"getImageInfo",
"getLaunchOptionsSync",
"getLeftWindowStyle",
"getLocale",
"getLocation",
"getNetworkType",
"getProvider",
"getPushClientId",
"getRealPath",
"getRecorderManager",
"getRightWindowStyle",
"getSavedFileInfo",
"getSavedFileList",
"getScreenBrightness",
"getSelectedTextRange",
"getStorage",
"getStorageInfo",
"getStorageInfoSync",
"getStorageSync",
"getSystemInfo",
"getSystemInfoSync",
"getTabBarPageId",
"getTopWindowStyle",
"getVideoInfo",
"getWindowInfo",
"hideActionSheet",
"hideKeyboard",
"hideLeftWindow",
"hideLoading",
"hideModal",
"hideNavigationBarLoading",
"hideRightWindow",
"hideTabBar",
"hideTabBarRedDot",
"hideToast",
"hideTopWindow",
"interceptors",
"invokePushCallback",
"loadFontFace",
"loadUasm",
"login",
"makePhoneCall",
"navigateBack",
"navigateTo",
"offAccelerometerChange",
"offAppHide",
"offAppRoute",
"offAppShow",
"offBeforeAppRoute",
"offCompassChange",
"offError",
"offHostThemeChange",
"offLocationChange",
"offLocationChangeError",
"offNetworkStatusChange",
"offPageNotFound",
"offPushMessage",
"offThemeChange",
"offUnhandledRejection",
"offWindowResize",
"onAccelerometerChange",
"onAppHide",
"onAppRoute",
"onAppShow",
"onBeforeAppRoute",
"onCompassChange",
"onCreateVueApp",
"onError",
"onGyroscopeChange",
"onHostThemeChange",
"onLocaleChange",
"onLocationChange",
"onLocationChangeError",
"onMemoryWarning",
"onNetworkStatusChange",
"onPageNotFound",
"onPushMessage",
"onSocketClose",
"onSocketError",
"onSocketMessage",
"onSocketOpen",
"onTabBarMidButtonTap",
"onThemeChange",
"onUnhandledRejection",
"onUserCaptureScreen",
"onWindowResize",
"openDialogPage",
"openDocument",
"openLocation",
"pageScrollTo",
"preloadPage",
"previewImage",
"reLaunch",
"redirectTo",
"removeAllPages",
"removeInterceptor",
"removeLastPage",
"removeNonTabBarPages",
"removeSavedFile",
"removeStorage",
"removeStorageSync",
"removeTabBarBadge",
"request",
"rewriteRoute",
"rpx2px",
"saveFile",
"saveImageToPhotosAlbum",
"saveVideoToPhotosAlbum",
"scanCode",
"sendSocketMessage",
"setClipboardData",
"setKeepScreenOn",
"setLeftWindowStyle",
"setLocale",
"setNavigationBarColor",
"setNavigationBarTitle",
"setPageMeta",
"setRightWindowStyle",
"setScreenBrightness",
"setStorage",
"setStorageSync",
"setTabBarBadge",
"setTabBarItem",
"setTabBarStyle",
"setTopWindowStyle",
"showActionSheet",
"showLeftWindow",
"showLoading",
"showModal",
"showNavigationBarLoading",
"showRightWindow",
"showTabBar",
"showTabBarRedDot",
"showToast",
"showTopWindow",
"startAccelerometer",
"startCompass",
"startGyroscope",
"startLocationUpdate",
"startPullDownRefresh",
"stopAccelerometer",
"stopCompass",
"stopGyroscope",
"stopLocationUpdate",
"stopPullDownRefresh",
"switchTab",
"uploadFile",
"upx2px",
"vibrateLong",
"vibrateShort"
]
@@ -0,0 +1,25 @@
'use strict'
const fs = require('fs')
const path = require('path')
const template = fs.readFileSync(
path.join(__dirname, './server/index.html'),
'utf-8'
)
const manifest = require('./server/ssr-manifest.json')
const render = require('./server/entry-server.js').render
exports.main = async (event) => {
const [appHtml, preloadLinks, appContext] = await render(event.path, manifest)
const html = template
.replace(`<!--preload-links-->`, preloadLinks)
.replace(`<!--app-html-->`, appHtml)
.replace(`<!--app-context-->`, appContext)
return {
mpserverlessComposedResponse: true, // 使用阿里云返回集成响应是需要此字段为true
statusCode: 200,
headers: {
'content-type': 'text/html',
},
body: html,
}
}
+27
View File
@@ -0,0 +1,27 @@
!(function () {
const defines = __DEFINES__
Object.keys(defines).forEach((key) => {
const segments = key.split('.')
let target = global
for (let i = 0; i < segments.length; i++) {
const segment = segments[i]
if (i === segments.length - 1) {
target[segment] = defines[key]
} else {
target = target[segment] || (target[segment] = {})
}
}
});
const { createRpx2Unit } = require('@dcloudio/uni-shared')
const rpx2unit = createRpx2Unit(__UNIT__, __UNIT_RATIO__, __UNIT_PRECISION__)
const shared = require('@vue/shared')
const oldStringifyStyle = shared.stringifyStyle
shared.stringifyStyle = (styles) => rpx2unit(oldStringifyStyle(styles))
const serverRender = require('@vue/server-renderer')
const oldSsrRenderStyle = serverRender.ssrRenderStyle
serverRender.ssrRenderStyle = (raw) =>
shared.isString(raw)
? rpx2unit(oldSsrRenderStyle(raw))
: oldSsrRenderStyle(raw)
})();
@@ -0,0 +1,99 @@
import { createApp } from './main'
import { renderToString } from '@vue/server-renderer'
import {
UNI_SSR,
UNI_SSR_DATA,
UNI_SSR_STORE,
UNI_SSR_TITLE,
UNI_SSR_GLOBAL_DATA,
} from '@dcloudio/uni-shared'
import { plugin } from '@dcloudio/uni-h5'
import { getSsrGlobalData } from '@dcloudio/uni-app'
export async function render(url, manifest = {}) {
const { app, store } = createApp()
app.use(plugin)
const router = app.router
// set the router to the desired URL before rendering
await router.push(url)
await router.isReady()
// passing SSR context object which will be available via useSSRContext()
// @vitejs/plugin-vue injects code into a component's setup() that registers
// itself on ctx.modules. After the render, ctx.modules would contain all the
// components that have been instantiated during this render call.
const ctx = {}
const appHtml = await renderToString(app, ctx)
// the SSR manifest generated by Vite contains module -> chunk/asset mapping
// which we can then use to determine what files need to be preloaded for this
// request.
const preloadLinks = renderPreloadLinks(ctx.modules, manifest)
// the SSR context
const __uniSSR = ctx[UNI_SSR] || (ctx[UNI_SSR] = {})
if (!__uniSSR[UNI_SSR_DATA]) {
__uniSSR[UNI_SSR_DATA] = {}
}
__uniSSR[UNI_SSR_GLOBAL_DATA] = getSsrGlobalData()
if (store) {
__uniSSR[UNI_SSR_STORE] = store.state
}
const appContext = renderAppContext(ctx)
const title = ctx[UNI_SSR_TITLE] || ''
const headMeta = renderHeadMeta(ctx)
return {
title,
headMeta,
preloadLinks,
appHtml,
appContext,
}
}
function renderPreloadLinks(modules, manifest) {
let links = ''
const seen = new Set()
modules.forEach((id) => {
const files = manifest[id]
if (files) {
files.forEach((file) => {
if (!seen.has(file)) {
seen.add(file)
links += renderPreloadLink(file)
}
})
}
})
return links
}
function renderPreloadLink(file) {
if (file.endsWith('.js')) {
return '<link rel="modulepreload" crossorigin href="' + file + '">'
} else if (file.endsWith('.css')) {
return '<link rel="stylesheet" href="' + file + '">'
} else {
// TODO
return ''
}
}
function renderAppContext(ctx) {
return `<script>window.__uniSSR = ${JSON.stringify(ctx[UNI_SSR])}</script>`
}
function renderHeadMeta(ctx) {
if (!ctx.__teleportBuffers || !ctx.__teleportBuffers.head) {
return ''
}
return ctx.__teleportBuffers.head
.map((buffer) =>
buffer
.toString()
.replace(/\s+data-v-[a-f0-9]{8}/gi, '')
.replace('<!--[-->', '')
.replace('<!--]--><!---->', '')
)
.join('\n')
}
+1
View File
@@ -0,0 +1 @@
[https://dcloud.io/license/uni-app.html](https://dcloud.io/license/uni-app.html)
+47
View File
@@ -0,0 +1,47 @@
{
"name": "@dcloudio/uni-h5-vite",
"version": "3.0.0-alpha-5030620261112001",
"description": "uni-h5-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-h5-vite"
},
"license": "Apache-2.0",
"gitHead": "33e807d66e1fe47e2ee08ad9c59247e37b8884da",
"dependencies": {
"@rollup/pluginutils": "5.1.0",
"@vitejs/plugin-basic-ssl": "1.2.0",
"@vue/compiler-dom": "3.4.21",
"@vue/compiler-sfc": "3.4.21",
"@vue/server-renderer": "3.4.21",
"@vue/shared": "3.4.21",
"debug": "4.3.7",
"estree-walker": "2.0.2",
"fs-extra": "10.1.0",
"hammer-touchemulator": "0.0.2",
"mime": "3.0.0",
"module-alias": "2.2.3",
"@dcloudio/uni-cli-shared": "3.0.0-alpha-5030620261112001",
"@dcloudio/uni-shared": "3.0.0-alpha-5030620261112001"
},
"devDependencies": {
"@types/debug": "4.1.12",
"@types/fs-extra": "9.0.13",
"@types/mime": "2.0.3",
"@types/module-alias": "2.0.4",
"@types/resolve": "1.20.6",
"@vue/compiler-core": "3.4.21",
"esbuild": "0.20.2",
"vue": "3.4.21"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
}
}