2025/2/8第一次更新

This commit is contained in:
爱吃咸鱼小猫咪
2025-02-08 18:50:38 +08:00
commit d7af560866
26519 changed files with 5046029 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;
+81
View File
@@ -0,0 +1,81 @@
"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 uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const plugin_1 = require("./plugin");
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 vueCompilerDom = __importStar(require("@vue/compiler-dom"));
const uniCliShared = __importStar(require("@dcloudio/uni-cli-shared"));
exports.default = [
...(process.env.UNI_APP_X === 'true'
? [
(0, uni_cli_shared_1.uniDecryptUniModulesPlugin)(),
(0, uni_cli_shared_1.uniUTSUVueJavaScriptPlugin)(),
(0, uni_cli_shared_1.resolveUTSCompiler)().uts2js({
inputDir: process.env.UNI_INPUT_DIR,
version: process.env.UNI_COMPILER_VERSION,
cacheRoot: path_1.default.resolve(process.env.UNI_APP_X_CACHE_DIR, '.uts2js/cache'),
modules: {
vueCompilerDom,
uniCliShared,
},
}),
]
: []),
(0, easycom_1.uniEasycomPlugin)({ exclude: uni_cli_shared_1.UNI_EASYCOM_EXCLUDE }),
(0, uni_cli_shared_1.uniCssScopedPlugin)({
filter: (id) => (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)(),
(0, plugin_1.uniH5Plugin)(),
...(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)(),
];
+4
View File
@@ -0,0 +1,4 @@
import type { Plugin, ResolvedConfig } from 'vite';
export declare function createConfig(options: {
resolvedConfig: ResolvedConfig | null;
}): Plugin['config'];
+113
View File
@@ -0,0 +1,113 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createConfig = void 0;
const os_1 = __importDefault(require("os"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../utils");
const esbuildPrePlugin_1 = require("./esbuild/esbuildPrePlugin");
const ssr_1 = require("./configureServer/ssr");
const shared_1 = require("@vue/shared");
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();
}
}
const server = {
host: true,
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/**')),
],
},
...(0, uni_cli_shared_1.getDevServerOptions)((0, uni_cli_shared_1.parseManifestJsonOnce)(inputDir)),
};
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);
}
}
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: ssr_1.external,
},
build: {
target: process.env.UNI_APP_X === 'true'
? ['es2015', 'edge79', 'firefox62', 'chrome64', 'safari11.1']
: undefined,
rollupOptions: {
// resolveSSRExternal 会判定package.jsonhbx 工程可能没有,通过 rollup 来配置
external: (0, uni_cli_shared_1.isSsr)(env.command, config) ? ssr_1.external : [],
output: {
chunkFileNames(chunkInfo) {
const { assetsDir } = options.resolvedConfig.build;
if (chunkInfo.facadeModuleId) {
const dirname = path_1.default.relative(inputDir, path_1.default.dirname(chunkInfo.facadeModuleId));
if (dirname) {
return path_1.default.posix.join(assetsDir, (0, uni_cli_shared_1.normalizePath)(dirname).replace(/\//g, '-') +
'-[name].[hash].js');
}
}
return path_1.default.posix.join(assetsDir, '[name].[hash].js');
},
},
},
},
};
};
}
exports.createConfig = createConfig;
@@ -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,3 @@
import type { ViteDevServer } from 'vite';
export declare const external: string[];
export declare function initSSR(server: ViteDevServer): void;
+57
View File
@@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initSSR = exports.external = void 0;
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',
];
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;
exports.external.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);
}
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,84 @@
"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 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/' +
(process.env.UNI_APP_X === 'true' ? 'dist-x' : 'dist') +
'/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 { options, 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: options.autoscan, custom: options.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);
}
+2
View File
@@ -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)(),
};
}
exports.uniH5Plugin = uniH5Plugin;
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function createTransformIndexHtml(): Plugin['transformIndexHtml'];
@@ -0,0 +1,48 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTransformIndexHtml = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function createTransformIndexHtml() {
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}`);
}
}
}
return {
html: html.replace(/<title>(.*?)<\/title>/, `<title>${title}</title>`),
tags: process.env.NODE_ENV === 'development'
? [
{
tag: 'script',
children: `if (typeof globalThis === 'undefined') {
window.globalThis = window
}`,
injectTo: 'head-prepend',
},
]
: [],
};
};
}
exports.createTransformIndexHtml = createTransformIndexHtml;
@@ -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;
+4
View File
@@ -0,0 +1,4 @@
import { type UniVitePlugin } from '@dcloudio/uni-cli-shared';
import type { CompilerOptions } from '@vue/compiler-core';
export declare const compilerOptions: CompilerOptions;
export declare function createUni(): UniVitePlugin['uni'];
+31
View File
@@ -0,0 +1,31 @@
"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");
function realIsH5CustomElement(tag) {
return (0, uni_shared_1.isH5CustomElement)(tag, process.env.UNI_APP_X === 'true');
}
exports.compilerOptions = {
isNativeTag: uni_shared_1.isH5NativeTag,
isCustomElement: realIsH5CustomElement,
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,
],
};
function createUni() {
return {
copyOptions: {
assets: ['hybrid/html/**/*', 'uni_modules/*/hybrid/html/**/*'],
},
compilerOptions: exports.compilerOptions,
jsxOptions: {
babelPlugins: [uni_cli_shared_1.transformUniH5Jsx],
},
};
}
exports.createUni = createUni;
+28
View File
@@ -0,0 +1,28 @@
/// <reference types="node" />
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 | Buffer): string;
+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.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 = '';
return {
name: 'uni:h5-css',
apply: 'build',
enforce: 'pre',
configResolved(config) {
resolvedConfig = config;
file = path_1.default.join(process.env.UNI_INPUT_DIR, 'uni.css');
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);
if (id.endsWith(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'shadow.css')) {
const url = (0, uni_cli_shared_1.createShadowImageUrl)(0, 'grey');
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')}');
}
.uni-page-head-shadow-blue::after {
background-image: url('${(0, uni_cli_shared_1.createShadowImageUrl)(0, 'blue')}');
}
.uni-page-head-shadow-green::after {
background-image: url('${(0, uni_cli_shared_1.createShadowImageUrl)(0, 'green')}');
}
.uni-page-head-shadow-orange::after {
background-image: url('${(0, uni_cli_shared_1.createShadowImageUrl)(0, 'orange')}');
}
.uni-page-head-shadow-red::after {
background-image: url('${(0, uni_cli_shared_1.createShadowImageUrl)(0, 'red')}');
}
.uni-page-head-shadow-yellow::after {
background-image: url('${(0, uni_cli_shared_1.createShadowImageUrl)(0, 'yellow')}');
}
`,
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) => fs_1.default.readFileSync((0, uni_cli_shared_1.resolveBuiltIn)(cssImport), 'utf8'))
.join('\n');
}
/**
* 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;
+8
View File
@@ -0,0 +1,8 @@
import type { Plugin } from 'vite';
import { type FilterPattern } from '@rollup/pluginutils';
interface UniEasycomPluginOptions {
include?: FilterPattern;
exclude?: FilterPattern;
}
export declare function uniEasycomPlugin(options: UniEasycomPluginOptions): Plugin;
export {};
+133
View File
@@ -0,0 +1,133 @@
"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 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 xBaseComponents = ['slider', 'switch'];
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');
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')) {
return;
}
let i = 0;
const importDeclarations = [];
code = code.replace(/_resolveComponent\("(.+?)"(, true)?\)/g, (str, name) => {
if (name && !name.startsWith('_')) {
if ((0, uni_shared_1.isBuiltInComponent)(name)) {
name = name.replace(uni_shared_1.COMPONENT_PREFIX, '');
const local = `__syscom_${i++}`;
if (needCombineBuiltInCss) {
// 发行模式下,应该将内置组件css输出到入口css中
resolveBuiltInCssImport(name).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);
}
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)) : ''));
}
}
return str;
});
if (importDeclarations.length) {
code = importDeclarations.join('') + code;
}
return {
code,
map: null,
};
},
};
}
exports.uniEasycomPlugin = uniEasycomPlugin;
function resolveBuiltInCssImport(name) {
const cssImports = [];
if (baseComponents.includes(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 {
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) {
resolveBuiltInCssImport(name).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)));
}
+2
View File
@@ -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;
+1
View File
@@ -0,0 +1 @@
export declare function uniMainJsPlugin(): import("vite").Plugin<any>;
+50
View File
@@ -0,0 +1,50 @@
"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() {
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')
? createApp(code)
: createLegacyApp(code);
}
else {
code = (0, utils_1.isSSR)(options)
? createSSRServerApp(code)
: createSSRClientApp(code);
}
code = `import './${uni_cli_shared_1.PAGES_JSON_JS}';${code}`;
return {
code,
map: this.getCombinedSourcemap(),
};
}
},
};
});
}
exports.uniMainJsPlugin = uniMainJsPlugin;
function createApp(code) {
return `import { plugin as __plugin } from '@dcloudio/uni-h5';${code.replace('createSSRApp', 'createVueApp as createSSRApp')};createApp().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) {
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;
}
+2
View File
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniManifestJsonPlugin(): Plugin;
+111
View File
@@ -0,0 +1,111 @@
"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);
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';
const platformConfig = manifest[process.env.UNI_PLATFORM === 'app'
? 'app-plus'
: process.env.UNI_PLATFORM] || {};
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 = ${platformConfig.darkmode || 'false'}
export const themeConfig = ${JSON.stringify((0, uni_cli_shared_1.normalizeThemeConfigOnce)(platformConfig))}
`,
map: { mappings: '' },
};
},
};
});
}
exports.uniManifestJsonPlugin = uniManifestJsonPlugin;
+2
View File
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniPagesJsonPlugin(): Plugin;
+261
View File
@@ -0,0 +1,261 @@
"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正确
code = code.replace(/\r\n/g, '\n');
try {
(0, uni_cli_shared_1.checkPagesJson)((0, uni_cli_shared_1.preUVueJson)(code), process.env.UNI_INPUT_DIR);
}
catch (err) {
if (err.loc) {
const error = (0, uni_cli_shared_1.createRollupError)('uni:app-pages', 'pages.json', err, code);
this.error(error);
}
else {
throw err;
}
}
}
return {
code: registerGlobalCode(resolvedConfig, ssr) +
generatePagesJsonCode(ssr, code, resolvedConfig),
map: { mappings: '' },
};
}
},
};
});
}
exports.uniPagesJsonPlugin = uniPagesJsonPlugin;
function generatePagesJsonCode(ssr, jsonStr, config) {
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);
const uniRoutesCode = generateRoutes(globalName, pagesJson, config);
const uniConfigCode = generateConfig(globalName, pagesJson, config);
const cssCode = generateCssCode(config);
const vueType = process.env.UNI_APP_X === 'true' ? 'uvue' : 'nvue';
return `
import { defineAsyncComponent, resolveComponent, createVNode, withCtx, openBlock, createBlock } from 'vue'
import { PageComponent, 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}
${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 (define.__UNI_FEATURE_TABBAR__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'tabBar.css');
}
// x 项目直接集成 uvue.css
if (process.env.UNI_APP_X === 'true') {
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(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 += `import ${name} from './${windowConfig.path}'\n`;
defineLayoutComponentsCode += `${globalName}.__uniConfig.${name}.component = setupWindow(${name},${windowNames[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))
const ${pageIdent} = defineAsyncComponent(extend({loader:${pageIdent}Loader},AsyncComponentOptions))`;
}
function generatePagesDefineCode(pagesJson, _config) {
const { pages } = pagesJson;
return (`const AsyncComponentOptions = {
delay: async.delay,
timeout: async.timeout,
suspensible: async.suspensible
}
if(async.loading){
AsyncComponentOptions.loadingComponent = {
name:'SystemAsyncLoading',
render(){
return createVNode(resolveComponent(async.loading))
}
}
}
if(async.error){
AsyncComponentOptions.errorComponent = {
name:'SystemAsyncError',
render(){
return createVNode(resolveComponent(async.error))
}
}
}
` + pages.map((pageOptions) => generatePageDefineCode(pageOptions)).join('\n'));
}
function generatePageRoute({ path, meta }, _config) {
const { isEntry } = meta;
const alias = isEntry ? `\n alias:'/${path}',` : '';
// 目前单页面未处理 query=>props
return `{
path:'/${isEntry ? '' : path}',${alias}
component:{setup(){ const app = getApp(); const query = app && app.$route && app.$route.query || {}; return ()=>renderPage(${(0, uni_cli_shared_1.normalizeIdentifier)(path)},query)}},
loader: ${(0, uni_cli_shared_1.normalizeIdentifier)(path)}Loader,
meta: ${JSON.stringify(meta)}
}`;
}
function generatePagesRoute(pagesRouteOptions, config) {
return pagesRouteOptions.map((pageOptions) => generatePageRoute(pageOptions, config));
}
function generateRoutes(globalName, pagesJson, config) {
return `
function renderPage(component,props){
return (openBlock(), createBlock(PageComponent, null, {page: withCtx(() => [createVNode(component, extend({},props,{ref: "page"}), null, 512 /* NEED_PATCH */)]), _: 1 /* STABLE */}))
}
${globalName}.__uniRoutes=[${[
...generatePagesRoute((0, uni_cli_shared_1.normalizePagesRoute)(pagesJson), config),
].join(',')}].map(uniRoute=>(uniRoute.meta.route = (uniRoute.alias || uniRoute.path).slice(1),uniRoute))`;
}
function generateConfig(globalName, pagesJson, config) {
delete pagesJson.pages;
delete pagesJson.subPackages;
delete pagesJson.subpackages;
pagesJson.compilerVersion = process.env.UNI_COMPILER_VERSION;
const isX = process.env.UNI_APP_X === 'true';
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}
`;
}
+2
View File
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniPostVuePlugin(): Plugin;
+48
View File
@@ -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];
}
+2
View File
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniRenderjsPlugin(): Plugin;
+47
View File
@@ -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 }})
}`;
}
+2
View File
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniResolveIdPlugin(): Plugin;
+51
View File
@@ -0,0 +1,51 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.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.join(utils_1.ownerModuleName, (process.env.UNI_APP_X === 'true' ? 'dist-x' : 'dist') +
'/uni-h5.es.js'));
resolveCache['@dcloudio/uni-h5-vue'] = (0, uni_cli_shared_1.resolveBuiltIn)(path_1.default.join('@dcloudio/uni-h5-vue', (process.env.UNI_APP_X === 'true' ? 'dist-x' : 'dist') +
`/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 === '@dcloudio/uni-h5-vue') {
return (0, uni_cli_shared_1.resolveBuiltIn)(path_1.default.join('@dcloudio/uni-h5-vue', (process.env.UNI_APP_X === 'true' ? 'dist-x' : 'dist') +
`/vue.runtime.cjs.js`));
}
}
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;
+2
View File
@@ -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;
+2
View File
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniPostSourceMapPlugin(): Plugin;
+57
View File
@@ -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);
}
}
+2
View File
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniSSRPlugin(): Plugin;
+67
View File
@@ -0,0 +1,67 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.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)();
(0, utils_1.rewriteSsrNativeTag)();
(0, utils_1.rewriteSsrRenderStyle)(process.env.UNI_INPUT_DIR);
return {
resolve: {
alias: [
{
find: 'vue/server-renderer',
replacement: path_1.default.dirname((0, uni_cli_shared_1.resolveBuiltIn)('@vue/server-renderer')),
},
{
find: 'vuex',
replacement: path_1.default.dirname((0, uni_cli_shared_1.resolveBuiltIn)('vuex/package.json')),
},
],
},
};
}
},
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;
+1
View File
@@ -0,0 +1 @@
export declare const ownerModuleName = "@dcloudio/uni-h5";
+4
View File
@@ -0,0 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ownerModuleName = void 0;
exports.ownerModuleName = '@dcloudio/uni-h5';
+2
View File
@@ -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;
+3
View File
@@ -0,0 +1,3 @@
export * from './ssr';
export * from './features';
export * from './constants';
+19
View File
@@ -0,0 +1,19 @@
"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);
+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;
+201
View File
@@ -0,0 +1,201 @@
"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");
// 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);
if (pkgData.module) {
pkgData.module = pkgData.module.replace(/dist\//, 'dist-x/');
}
if (pkgData.main) {
pkgData.main = pkgData.main.replace(/dist\//, 'dist-x/');
}
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 的映射
require('module-alias').addAliases({
vue: (0, uni_cli_shared_1.resolveBuiltIn)('@dcloudio/uni-h5-vue/' +
(process.env.UNI_APP_X === 'true' ? 'dist-x' : 'dist') +
'/vue.runtime.cjs.js'),
'vue/package.json': (0, uni_cli_shared_1.resolveBuiltIn)('@dcloudio/uni-h5-vue/package.json'),
});
// 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/' +
(process.env.UNI_APP_X === 'true' ? 'dist-x' : 'dist') +
'/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;
+181
View File
@@ -0,0 +1,181 @@
[
"$emit",
"$off",
"$on",
"$once",
"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",
"getElementById",
"getEnterOptionsSync",
"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"
]
+184
View File
@@ -0,0 +1,184 @@
[
"$emit",
"$off",
"$on",
"$once",
"addInterceptor",
"addPhoneContact",
"arrayBufferToBase64",
"base64ToArrayBuffer",
"canIUse",
"canvasGetImageData",
"canvasPutImageData",
"canvasToTempFilePath",
"chooseFile",
"chooseImage",
"chooseLocation",
"chooseVideo",
"clearStorage",
"clearStorageSync",
"closeDialogPage",
"closePreviewImage",
"closeSocket",
"connectSocket",
"createAnimation",
"createCameraContext",
"createCanvasContext",
"createCanvasContextAsync",
"createInnerAudioContext",
"createIntersectionObserver",
"createLivePlayerContext",
"createMapContext",
"createMediaQueryObserver",
"createSelectorQuery",
"createVideoContext",
"downloadFile",
"getAppBaseInfo",
"getClipboardData",
"getDeviceInfo",
"getElementById",
"getEnterOptionsSync",
"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",
"openDialogPage",
"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"
]
+25
View File
@@ -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)
})();
+99
View File
@@ -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)
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018-present, Yuxi (Evan) You
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,19 @@
# @vue/reactivity
## Usage Note
This package is inlined into Global & Browser ESM builds of user-facing renderers (e.g. `@vue/runtime-dom`), but also published as a package that can be used standalone. The standalone build should not be used alongside a pre-bundled build of a user-facing renderer, as they will have different internal storage for reactivity connections. A user-facing renderer should re-export all APIs from this package.
For full exposed APIs, see `src/index.ts`.
## Credits
The implementation of this module is inspired by the following prior art in the JavaScript ecosystem:
- [Meteor Tracker](https://docs.meteor.com/api/tracker.html)
- [nx-js/observer-util](https://github.com/nx-js/observer-util)
- [salesforce/observable-membrane](https://github.com/salesforce/observable-membrane)
## Caveats
- Built-in objects are not observed except for `Array`, `Map`, `WeakMap`, `Set` and `WeakSet`.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,662 @@
import { IfAny } from '@vue/shared';
export declare enum TrackOpTypes {
GET = "get",
HAS = "has",
ITERATE = "iterate"
}
export declare enum TriggerOpTypes {
SET = "set",
ADD = "add",
DELETE = "delete",
CLEAR = "clear"
}
export declare enum ReactiveFlags {
SKIP = "__v_skip",
IS_REACTIVE = "__v_isReactive",
IS_READONLY = "__v_isReadonly",
IS_SHALLOW = "__v_isShallow",
RAW = "__v_raw"
}
type Dep = Map<ReactiveEffect, number> & {
cleanup: () => void;
computed?: ComputedRefImpl<any>;
};
export declare class EffectScope {
detached: boolean;
constructor(detached?: boolean);
get active(): boolean;
run<T>(fn: () => T): T | undefined;
stop(fromParent?: boolean): void;
}
/**
* Creates an effect scope object which can capture the reactive effects (i.e.
* computed and watchers) created within it so that these effects can be
* disposed together. For detailed use cases of this API, please consult its
* corresponding {@link https://github.com/vuejs/rfcs/blob/master/active-rfcs/0041-reactivity-effect-scope.md | RFC}.
*
* @param detached - Can be used to create a "detached" effect scope.
* @see {@link https://vuejs.org/api/reactivity-advanced.html#effectscope}
*/
export declare function effectScope(detached?: boolean): EffectScope;
/**
* Returns the current active effect scope if there is one.
*
* @see {@link https://vuejs.org/api/reactivity-advanced.html#getcurrentscope}
*/
export declare function getCurrentScope(): EffectScope | undefined;
/**
* Registers a dispose callback on the current active effect scope. The
* callback will be invoked when the associated effect scope is stopped.
*
* @param fn - The callback function to attach to the scope's cleanup.
* @see {@link https://vuejs.org/api/reactivity-advanced.html#onscopedispose}
*/
export declare function onScopeDispose(fn: () => void): void;
export type EffectScheduler = (...args: any[]) => any;
export type DebuggerEvent = {
effect: ReactiveEffect;
} & DebuggerEventExtraInfo;
export type DebuggerEventExtraInfo = {
target: object;
type: TrackOpTypes | TriggerOpTypes;
key: any;
newValue?: any;
oldValue?: any;
oldTarget?: Map<any, any> | Set<any>;
};
export declare class ReactiveEffect<T = any> {
fn: () => T;
trigger: () => void;
scheduler?: EffectScheduler | undefined;
active: boolean;
deps: Dep[];
onStop?: () => void;
onTrack?: (event: DebuggerEvent) => void;
onTrigger?: (event: DebuggerEvent) => void;
constructor(fn: () => T, trigger: () => void, scheduler?: EffectScheduler | undefined, scope?: EffectScope);
get dirty(): boolean;
set dirty(v: boolean);
run(): T;
stop(): void;
}
export interface DebuggerOptions {
onTrack?: (event: DebuggerEvent) => void;
onTrigger?: (event: DebuggerEvent) => void;
}
export interface ReactiveEffectOptions extends DebuggerOptions {
lazy?: boolean;
scheduler?: EffectScheduler;
scope?: EffectScope;
allowRecurse?: boolean;
onStop?: () => void;
}
export interface ReactiveEffectRunner<T = any> {
(): T;
effect: ReactiveEffect;
}
/**
* Registers the given function to track reactive updates.
*
* The given function will be run once immediately. Every time any reactive
* property that's accessed within it gets updated, the function will run again.
*
* @param fn - The function that will track reactive updates.
* @param options - Allows to control the effect's behaviour.
* @returns A runner that can be used to control the effect after creation.
*/
export declare function effect<T = any>(fn: () => T, options?: ReactiveEffectOptions): ReactiveEffectRunner;
/**
* Stops the effect associated with the given runner.
*
* @param runner - Association with the effect to stop tracking.
*/
export declare function stop(runner: ReactiveEffectRunner): void;
/**
* Temporarily pauses tracking.
*/
export declare function pauseTracking(): void;
/**
* Re-enables effect tracking (if it was paused).
*/
export declare function enableTracking(): void;
/**
* Resets the previous global effect tracking state.
*/
export declare function resetTracking(): void;
export declare function pauseScheduling(): void;
export declare function resetScheduling(): void;
declare const ComputedRefSymbol: unique symbol;
export interface ComputedRef<T = any> extends WritableComputedRef<T> {
readonly value: T;
[ComputedRefSymbol]: true;
}
export interface WritableComputedRef<T> extends Ref<T> {
readonly effect: ReactiveEffect<T>;
}
export type ComputedGetter<T> = (oldValue?: T) => T;
export type ComputedSetter<T> = (newValue: T) => void;
export interface WritableComputedOptions<T> {
get: ComputedGetter<T>;
set: ComputedSetter<T>;
}
export declare class ComputedRefImpl<T> {
private getter;
private readonly _setter;
dep?: Dep;
private _value;
readonly effect: ReactiveEffect<T>;
readonly __v_isRef = true;
readonly [ReactiveFlags.IS_READONLY]: boolean;
_cacheable: boolean;
/**
* Dev only
*/
_warnRecursive?: boolean;
constructor(getter: ComputedGetter<T>, _setter: ComputedSetter<T>, isReadonly: boolean, isSSR: boolean);
get value(): T;
set value(newValue: T);
get _dirty(): boolean;
set _dirty(v: boolean);
}
/**
* Takes a getter function and returns a readonly reactive ref object for the
* returned value from the getter. It can also take an object with get and set
* functions to create a writable ref object.
*
* @example
* ```js
* // Creating a readonly computed ref:
* const count = ref(1)
* const plusOne = computed(() => count.value + 1)
*
* console.log(plusOne.value) // 2
* plusOne.value++ // error
* ```
*
* ```js
* // Creating a writable computed ref:
* const count = ref(1)
* const plusOne = computed({
* get: () => count.value + 1,
* set: (val) => {
* count.value = val - 1
* }
* })
*
* plusOne.value = 1
* console.log(count.value) // 0
* ```
*
* @param getter - Function that produces the next value.
* @param debugOptions - For debugging. See {@link https://vuejs.org/guide/extras/reactivity-in-depth.html#computed-debugging}.
* @see {@link https://vuejs.org/api/reactivity-core.html#computed}
*/
export declare function computed<T>(getter: ComputedGetter<T>, debugOptions?: DebuggerOptions): ComputedRef<T>;
export declare function computed<T>(options: WritableComputedOptions<T>, debugOptions?: DebuggerOptions): WritableComputedRef<T>;
export type UnwrapNestedRefs<T> = T extends Ref ? T : UnwrapRefSimple<T>;
/**
* Returns a reactive proxy of the object.
*
* The reactive conversion is "deep": it affects all nested properties. A
* reactive object also deeply unwraps any properties that are refs while
* maintaining reactivity.
*
* @example
* ```js
* const obj = reactive({ count: 0 })
* ```
*
* @param target - The source object.
* @see {@link https://vuejs.org/api/reactivity-core.html#reactive}
*/
export declare function reactive<T extends object>(target: T): UnwrapNestedRefs<T>;
declare const ShallowReactiveMarker: unique symbol;
export type ShallowReactive<T> = T & {
[ShallowReactiveMarker]?: true;
};
/**
* Shallow version of {@link reactive()}.
*
* Unlike {@link reactive()}, there is no deep conversion: only root-level
* properties are reactive for a shallow reactive object. Property values are
* stored and exposed as-is - this also means properties with ref values will
* not be automatically unwrapped.
*
* @example
* ```js
* const state = shallowReactive({
* foo: 1,
* nested: {
* bar: 2
* }
* })
*
* // mutating state's own properties is reactive
* state.foo++
*
* // ...but does not convert nested objects
* isReactive(state.nested) // false
*
* // NOT reactive
* state.nested.bar++
* ```
*
* @param target - The source object.
* @see {@link https://vuejs.org/api/reactivity-advanced.html#shallowreactive}
*/
export declare function shallowReactive<T extends object>(target: T): ShallowReactive<T>;
type Primitive = string | number | boolean | bigint | symbol | undefined | null;
type Builtin = Primitive | Function | Date | Error | RegExp;
export type DeepReadonly<T> = T extends Builtin ? T : T extends Map<infer K, infer V> ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>> : T extends ReadonlyMap<infer K, infer V> ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>> : T extends WeakMap<infer K, infer V> ? WeakMap<DeepReadonly<K>, DeepReadonly<V>> : T extends Set<infer U> ? ReadonlySet<DeepReadonly<U>> : T extends ReadonlySet<infer U> ? ReadonlySet<DeepReadonly<U>> : T extends WeakSet<infer U> ? WeakSet<DeepReadonly<U>> : T extends Promise<infer U> ? Promise<DeepReadonly<U>> : T extends Ref<infer U> ? Readonly<Ref<DeepReadonly<U>>> : T extends {} ? {
readonly [K in keyof T]: DeepReadonly<T[K]>;
} : Readonly<T>;
/**
* Takes an object (reactive or plain) or a ref and returns a readonly proxy to
* the original.
*
* A readonly proxy is deep: any nested property accessed will be readonly as
* well. It also has the same ref-unwrapping behavior as {@link reactive()},
* except the unwrapped values will also be made readonly.
*
* @example
* ```js
* const original = reactive({ count: 0 })
*
* const copy = readonly(original)
*
* watchEffect(() => {
* // works for reactivity tracking
* console.log(copy.count)
* })
*
* // mutating original will trigger watchers relying on the copy
* original.count++
*
* // mutating the copy will fail and result in a warning
* copy.count++ // warning!
* ```
*
* @param target - The source object.
* @see {@link https://vuejs.org/api/reactivity-core.html#readonly}
*/
export declare function readonly<T extends object>(target: T): DeepReadonly<UnwrapNestedRefs<T>>;
/**
* Shallow version of {@link readonly()}.
*
* Unlike {@link readonly()}, there is no deep conversion: only root-level
* properties are made readonly. Property values are stored and exposed as-is -
* this also means properties with ref values will not be automatically
* unwrapped.
*
* @example
* ```js
* const state = shallowReadonly({
* foo: 1,
* nested: {
* bar: 2
* }
* })
*
* // mutating state's own properties will fail
* state.foo++
*
* // ...but works on nested objects
* isReadonly(state.nested) // false
*
* // works
* state.nested.bar++
* ```
*
* @param target - The source object.
* @see {@link https://vuejs.org/api/reactivity-advanced.html#shallowreadonly}
*/
export declare function shallowReadonly<T extends object>(target: T): Readonly<T>;
/**
* Checks if an object is a proxy created by {@link reactive()} or
* {@link shallowReactive()} (or {@link ref()} in some cases).
*
* @example
* ```js
* isReactive(reactive({})) // => true
* isReactive(readonly(reactive({}))) // => true
* isReactive(ref({}).value) // => true
* isReactive(readonly(ref({})).value) // => true
* isReactive(ref(true)) // => false
* isReactive(shallowRef({}).value) // => false
* isReactive(shallowReactive({})) // => true
* ```
*
* @param value - The value to check.
* @see {@link https://vuejs.org/api/reactivity-utilities.html#isreactive}
*/
export declare function isReactive(value: unknown): boolean;
/**
* Checks whether the passed value is a readonly object. The properties of a
* readonly object can change, but they can't be assigned directly via the
* passed object.
*
* The proxies created by {@link readonly()} and {@link shallowReadonly()} are
* both considered readonly, as is a computed ref without a set function.
*
* @param value - The value to check.
* @see {@link https://vuejs.org/api/reactivity-utilities.html#isreadonly}
*/
export declare function isReadonly(value: unknown): boolean;
export declare function isShallow(value: unknown): boolean;
/**
* Checks if an object is a proxy created by {@link reactive},
* {@link readonly}, {@link shallowReactive} or {@link shallowReadonly()}.
*
* @param value - The value to check.
* @see {@link https://vuejs.org/api/reactivity-utilities.html#isproxy}
*/
export declare function isProxy(value: unknown): boolean;
/**
* Returns the raw, original object of a Vue-created proxy.
*
* `toRaw()` can return the original object from proxies created by
* {@link reactive()}, {@link readonly()}, {@link shallowReactive()} or
* {@link shallowReadonly()}.
*
* This is an escape hatch that can be used to temporarily read without
* incurring proxy access / tracking overhead or write without triggering
* changes. It is **not** recommended to hold a persistent reference to the
* original object. Use with caution.
*
* @example
* ```js
* const foo = {}
* const reactiveFoo = reactive(foo)
*
* console.log(toRaw(reactiveFoo) === foo) // true
* ```
*
* @param observed - The object for which the "raw" value is requested.
* @see {@link https://vuejs.org/api/reactivity-advanced.html#toraw}
*/
export declare function toRaw<T>(observed: T): T;
export type Raw<T> = T & {
[RawSymbol]?: true;
};
/**
* Marks an object so that it will never be converted to a proxy. Returns the
* object itself.
*
* @example
* ```js
* const foo = markRaw({})
* console.log(isReactive(reactive(foo))) // false
*
* // also works when nested inside other reactive objects
* const bar = reactive({ foo })
* console.log(isReactive(bar.foo)) // false
* ```
*
* **Warning:** `markRaw()` together with the shallow APIs such as
* {@link shallowReactive()} allow you to selectively opt-out of the default
* deep reactive/readonly conversion and embed raw, non-proxied objects in your
* state graph.
*
* @param value - The object to be marked as "raw".
* @see {@link https://vuejs.org/api/reactivity-advanced.html#markraw}
*/
export declare function markRaw<T extends object>(value: T): Raw<T>;
declare const RefSymbol: unique symbol;
declare const RawSymbol: unique symbol;
export interface Ref<T = any> {
value: T;
/**
* Type differentiator only.
* We need this to be in public d.ts but don't want it to show up in IDE
* autocomplete, so we use a private Symbol instead.
*/
[RefSymbol]: true;
}
/**
* Checks if a value is a ref object.
*
* @param r - The value to inspect.
* @see {@link https://vuejs.org/api/reactivity-utilities.html#isref}
*/
export declare function isRef<T>(r: Ref<T> | unknown): r is Ref<T>;
/**
* Takes an inner value and returns a reactive and mutable ref object, which
* has a single property `.value` that points to the inner value.
*
* @param value - The object to wrap in the ref.
* @see {@link https://vuejs.org/api/reactivity-core.html#ref}
*/
export declare function ref<T>(value: T): Ref<UnwrapRef<T>>;
export declare function ref<T = any>(): Ref<T | undefined>;
declare const ShallowRefMarker: unique symbol;
export type ShallowRef<T = any> = Ref<T> & {
[ShallowRefMarker]?: true;
};
/**
* Shallow version of {@link ref()}.
*
* @example
* ```js
* const state = shallowRef({ count: 1 })
*
* // does NOT trigger change
* state.value.count = 2
*
* // does trigger change
* state.value = { count: 2 }
* ```
*
* @param value - The "inner value" for the shallow ref.
* @see {@link https://vuejs.org/api/reactivity-advanced.html#shallowref}
*/
export declare function shallowRef<T>(value: T): Ref extends T ? T extends Ref ? IfAny<T, ShallowRef<T>, T> : ShallowRef<T> : ShallowRef<T>;
export declare function shallowRef<T = any>(): ShallowRef<T | undefined>;
/**
* Force trigger effects that depends on a shallow ref. This is typically used
* after making deep mutations to the inner value of a shallow ref.
*
* @example
* ```js
* const shallow = shallowRef({
* greet: 'Hello, world'
* })
*
* // Logs "Hello, world" once for the first run-through
* watchEffect(() => {
* console.log(shallow.value.greet)
* })
*
* // This won't trigger the effect because the ref is shallow
* shallow.value.greet = 'Hello, universe'
*
* // Logs "Hello, universe"
* triggerRef(shallow)
* ```
*
* @param ref - The ref whose tied effects shall be executed.
* @see {@link https://vuejs.org/api/reactivity-advanced.html#triggerref}
*/
export declare function triggerRef(ref: Ref): void;
export type MaybeRef<T = any> = T | Ref<T>;
export type MaybeRefOrGetter<T = any> = MaybeRef<T> | (() => T);
/**
* Returns the inner value if the argument is a ref, otherwise return the
* argument itself. This is a sugar function for
* `val = isRef(val) ? val.value : val`.
*
* @example
* ```js
* function useFoo(x: number | Ref<number>) {
* const unwrapped = unref(x)
* // unwrapped is guaranteed to be number now
* }
* ```
*
* @param ref - Ref or plain value to be converted into the plain value.
* @see {@link https://vuejs.org/api/reactivity-utilities.html#unref}
*/
export declare function unref<T>(ref: MaybeRef<T> | ComputedRef<T>): T;
/**
* Normalizes values / refs / getters to values.
* This is similar to {@link unref()}, except that it also normalizes getters.
* If the argument is a getter, it will be invoked and its return value will
* be returned.
*
* @example
* ```js
* toValue(1) // 1
* toValue(ref(1)) // 1
* toValue(() => 1) // 1
* ```
*
* @param source - A getter, an existing ref, or a non-function value.
* @see {@link https://vuejs.org/api/reactivity-utilities.html#tovalue}
*/
export declare function toValue<T>(source: MaybeRefOrGetter<T> | ComputedRef<T>): T;
/**
* Returns a reactive proxy for the given object.
*
* If the object already is reactive, it's returned as-is. If not, a new
* reactive proxy is created. Direct child properties that are refs are properly
* handled, as well.
*
* @param objectWithRefs - Either an already-reactive object or a simple object
* that contains refs.
*/
export declare function proxyRefs<T extends object>(objectWithRefs: T): ShallowUnwrapRef<T>;
export type CustomRefFactory<T> = (track: () => void, trigger: () => void) => {
get: () => T;
set: (value: T) => void;
};
/**
* Creates a customized ref with explicit control over its dependency tracking
* and updates triggering.
*
* @param factory - The function that receives the `track` and `trigger` callbacks.
* @see {@link https://vuejs.org/api/reactivity-advanced.html#customref}
*/
export declare function customRef<T>(factory: CustomRefFactory<T>): Ref<T>;
export type ToRefs<T = any> = {
[K in keyof T]: ToRef<T[K]>;
};
/**
* Converts a reactive object to a plain object where each property of the
* resulting object is a ref pointing to the corresponding property of the
* original object. Each individual ref is created using {@link toRef()}.
*
* @param object - Reactive object to be made into an object of linked refs.
* @see {@link https://vuejs.org/api/reactivity-utilities.html#torefs}
*/
export declare function toRefs<T extends object>(object: T): ToRefs<T>;
export type ToRef<T> = IfAny<T, Ref<T>, [T] extends [Ref] ? T : Ref<T>>;
/**
* Used to normalize values / refs / getters into refs.
*
* @example
* ```js
* // returns existing refs as-is
* toRef(existingRef)
*
* // creates a ref that calls the getter on .value access
* toRef(() => props.foo)
*
* // creates normal refs from non-function values
* // equivalent to ref(1)
* toRef(1)
* ```
*
* Can also be used to create a ref for a property on a source reactive object.
* The created ref is synced with its source property: mutating the source
* property will update the ref, and vice-versa.
*
* @example
* ```js
* const state = reactive({
* foo: 1,
* bar: 2
* })
*
* const fooRef = toRef(state, 'foo')
*
* // mutating the ref updates the original
* fooRef.value++
* console.log(state.foo) // 2
*
* // mutating the original also updates the ref
* state.foo++
* console.log(fooRef.value) // 3
* ```
*
* @param source - A getter, an existing ref, a non-function value, or a
* reactive object to create a property ref from.
* @param [key] - (optional) Name of the property in the reactive object.
* @see {@link https://vuejs.org/api/reactivity-utilities.html#toref}
*/
export declare function toRef<T>(value: T): T extends () => infer R ? Readonly<Ref<R>> : T extends Ref ? T : Ref<UnwrapRef<T>>;
export declare function toRef<T extends object, K extends keyof T>(object: T, key: K): ToRef<T[K]>;
export declare function toRef<T extends object, K extends keyof T>(object: T, key: K, defaultValue: T[K]): ToRef<Exclude<T[K], undefined>>;
type BaseTypes = string | number | boolean;
/**
* This is a special exported interface for other packages to declare
* additional types that should bail out for ref unwrapping. For example
* \@vue/runtime-dom can declare it like so in its d.ts:
*
* ``` ts
* declare module '@vue/reactivity' {
* export interface RefUnwrapBailTypes {
* runtimeDOMBailTypes: Node | Window
* }
* }
* ```
*/
export interface RefUnwrapBailTypes {
}
export type ShallowUnwrapRef<T> = {
[K in keyof T]: DistrubuteRef<T[K]>;
};
type DistrubuteRef<T> = T extends Ref<infer V> ? V : T;
export type UnwrapRef<T> = T extends ShallowRef<infer V> ? V : T extends Ref<infer V> ? UnwrapRefSimple<V> : UnwrapRefSimple<T>;
type UnwrapRefSimple<T> = T extends Function | BaseTypes | Ref | RefUnwrapBailTypes[keyof RefUnwrapBailTypes] | {
[RawSymbol]?: true;
} ? T : T extends Map<infer K, infer V> ? Map<K, UnwrapRefSimple<V>> & UnwrapRef<Omit<T, keyof Map<any, any>>> : T extends WeakMap<infer K, infer V> ? WeakMap<K, UnwrapRefSimple<V>> & UnwrapRef<Omit<T, keyof WeakMap<any, any>>> : T extends Set<infer V> ? Set<UnwrapRefSimple<V>> & UnwrapRef<Omit<T, keyof Set<any>>> : T extends WeakSet<infer V> ? WeakSet<UnwrapRefSimple<V>> & UnwrapRef<Omit<T, keyof WeakSet<any>>> : T extends ReadonlyArray<any> ? {
[K in keyof T]: UnwrapRefSimple<T[K]>;
} : T extends object & {
[ShallowReactiveMarker]?: never;
} ? {
[P in keyof T]: P extends symbol ? T[P] : UnwrapRef<T[P]>;
} : T;
/**
* @deprecated use `computed` instead. See #5912
*/
export declare const deferredComputed: typeof computed;
export declare const ITERATE_KEY: unique symbol;
/**
* Tracks access to a reactive property.
*
* This will check which effect is running at the moment and record it as dep
* which records all effects that depend on the reactive property.
*
* @param target - Object holding the reactive property.
* @param type - Defines the type of access to the reactive property.
* @param key - Identifier of the reactive property to track.
*/
export declare function track(target: object, type: TrackOpTypes, key: unknown): void;
/**
* Finds all deps associated with the target (or a specific property) and
* triggers the effects stored within.
*
* @param target - The reactive object.
* @param type - Defines the type of the operation that needs to trigger effects.
* @param key - Can be used to target a specific reactive property in the target object.
*/
export declare function trigger(target: object, type: TriggerOpTypes, key?: unknown, newValue?: unknown, oldValue?: unknown, oldTarget?: Map<unknown, unknown> | Set<unknown>): void;
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,7 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/reactivity.cjs.prod.js')
} else {
module.exports = require('./dist/reactivity.cjs.js')
}
@@ -0,0 +1,55 @@
{
"name": "@vue/reactivity",
"version": "3.4.21",
"description": "@vue/reactivity",
"main": "index.js",
"module": "dist/reactivity.esm-bundler.js",
"types": "dist/reactivity.d.ts",
"unpkg": "dist/reactivity.global.js",
"jsdelivr": "dist/reactivity.global.js",
"files": [
"index.js",
"dist"
],
"exports": {
".": {
"types": "./dist/reactivity.d.ts",
"node": {
"production": "./dist/reactivity.cjs.prod.js",
"development": "./dist/reactivity.cjs.js",
"default": "./index.js"
},
"module": "./dist/reactivity.esm-bundler.js",
"import": "./dist/reactivity.esm-bundler.js",
"require": "./index.js"
},
"./*": "./*"
},
"sideEffects": false,
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/core.git",
"directory": "packages/reactivity"
},
"buildOptions": {
"name": "VueReactivity",
"formats": [
"esm-bundler",
"esm-browser",
"cjs",
"global"
]
},
"keywords": [
"vue"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/core/issues"
},
"homepage": "https://github.com/vuejs/core/tree/main/packages/reactivity#readme",
"dependencies": {
"@vue/shared": "3.4.21"
}
}
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018-present, Yuxi (Evan) You
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,28 @@
# @vue/runtime-core
> This package is published only for typing and building custom renderers. It is NOT meant to be used in applications.
For full exposed APIs, see `src/index.ts`.
## Building a Custom Renderer
```ts
import { createRenderer } from '@vue/runtime-core'
const { render, createApp } = createRenderer({
patchProp,
insert,
remove,
createElement
// ...
})
// `render` is the low-level API
// `createApp` returns an app instance with configurable context shared
// by the entire app tree.
export { render, createApp }
export * from '@vue/runtime-core'
```
See `@vue/runtime-dom` for how a DOM-targeting renderer is implemented.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,7 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/runtime-core.cjs.prod.js')
} else {
module.exports = require('./dist/runtime-core.cjs.js')
}
@@ -0,0 +1,52 @@
{
"name": "@vue/runtime-core",
"version": "3.4.21",
"description": "@vue/runtime-core",
"main": "index.js",
"module": "dist/runtime-core.esm-bundler.js",
"types": "dist/runtime-core.d.ts",
"files": [
"index.js",
"dist"
],
"exports": {
".": {
"types": "./dist/runtime-core.d.ts",
"node": {
"production": "./dist/runtime-core.cjs.prod.js",
"development": "./dist/runtime-core.cjs.js",
"default": "./index.js"
},
"module": "./dist/runtime-core.esm-bundler.js",
"import": "./dist/runtime-core.esm-bundler.js",
"require": "./index.js"
},
"./*": "./*"
},
"buildOptions": {
"name": "VueRuntimeCore",
"formats": [
"esm-bundler",
"cjs"
]
},
"sideEffects": false,
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/core.git",
"directory": "packages/runtime-core"
},
"keywords": [
"vue"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/core/issues"
},
"homepage": "https://github.com/vuejs/core/tree/main/packages/runtime-core#readme",
"dependencies": {
"@vue/shared": "3.4.21",
"@vue/reactivity": "3.4.21"
}
}
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018-present, Yuxi (Evan) You
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,13 @@
# @vue/runtime-dom
``` js
import { h, createApp } from '@vue/runtime-dom'
const RootComponent = {
render() {
return h('div', 'hello world')
}
}
createApp(RootComponent).mount('#app')
```
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,7 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/runtime-dom.cjs.prod.js')
} else {
module.exports = require('./dist/runtime-dom.cjs.js')
}
@@ -0,0 +1,56 @@
{
"name": "@vue/runtime-dom",
"version": "3.4.21",
"description": "@vue/runtime-dom",
"main": "index.js",
"module": "dist/runtime-dom.esm-bundler.js",
"types": "dist/runtime-dom.d.ts",
"unpkg": "dist/runtime-dom.global.js",
"files": [
"index.js",
"dist"
],
"exports": {
".": {
"types": "./dist/runtime-dom.d.ts",
"node": {
"production": "./dist/runtime-dom.cjs.prod.js",
"development": "./dist/runtime-dom.cjs.js",
"default": "./index.js"
},
"module": "./dist/runtime-dom.esm-bundler.js",
"import": "./dist/runtime-dom.esm-bundler.js",
"require": "./index.js"
},
"./*": "./*"
},
"sideEffects": false,
"buildOptions": {
"name": "VueRuntimeDOM",
"formats": [
"esm-bundler",
"esm-browser",
"cjs",
"global"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/core.git",
"directory": "packages/runtime-dom"
},
"keywords": [
"vue"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/core/issues"
},
"homepage": "https://github.com/vuejs/core/tree/main/packages/runtime-dom#readme",
"dependencies": {
"csstype": "^3.1.3",
"@vue/shared": "3.4.21",
"@vue/runtime-core": "3.4.21"
}
}
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018-present, Yuxi (Evan) You
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,178 @@
# @vue/server-renderer
**Note: as of 3.2.13+, this package is included as a dependency of the main `vue` package and can be accessed as `vue/server-renderer`. This means you no longer need to explicitly install this package and ensure its version match that of `vue`'s. Just use the `vue/server-renderer` deep import instead.**
## Basic API
### `renderToString`
**Signature**
```ts
function renderToString(
input: App | VNode,
context?: SSRContext
): Promise<string>
```
**Usage**
```js
const { createSSRApp } = require('vue')
const { renderToString } = require('@vue/server-renderer')
const app = createSSRApp({
data: () => ({ msg: 'hello' }),
template: `<div>{{ msg }}</div>`
})
;(async () => {
const html = await renderToString(app)
console.log(html)
})()
```
### Handling Teleports
If the rendered app contains teleports, the teleported content will not be part of the rendered string. Instead, they are exposed under the `teleports` property of the ssr context object:
```js
const ctx = {}
const html = await renderToString(app, ctx)
console.log(ctx.teleports) // { '#teleported': 'teleported content' }
```
## Streaming API
### `renderToNodeStream`
Renders input as a [Node.js Readable stream](https://nodejs.org/api/stream.html#stream_class_stream_readable).
**Signature**
```ts
function renderToNodeStream(input: App | VNode, context?: SSRContext): Readable
```
**Usage**
```js
// inside a Node.js http handler
renderToNodeStream(app).pipe(res)
```
**Note:** This method is not supported in the ESM build of `@vue/server-renderer`, which is decoupled from Node.js environments. Use `pipeToNodeWritable` instead.
### `pipeToNodeWritable`
Render and pipe to an existing [Node.js Writable stream](https://nodejs.org/api/stream.html#stream_writable_streams) instance.
**Signature**
```ts
function pipeToNodeWritable(
input: App | VNode,
context: SSRContext = {},
writable: Writable
): void
```
**Usage**
```js
// inside a Node.js http handler
pipeToNodeWritable(app, {}, res)
```
### `renderToWebStream`
Renders input as a [Web ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API).
**Signature**
```ts
function renderToWebStream(
input: App | VNode,
context?: SSRContext
): ReadableStream
```
**Usage**
```js
// inside an environment with ReadableStream support
return new Response(renderToWebStream(app))
```
**Note:** in environments that do not expose `ReadableStream` constructor in the global scope, `pipeToWebWritable` should be used instead.
### `pipeToWebWritable`
Render and pipe to an existing [Web WritableStream](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream) instance.
**Signature**
```ts
function pipeToWebWritable(
input: App | VNode,
context: SSRContext = {},
writable: WritableStream
): void
```
**Usage**
This is typically used in combination with [`TransformStream`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream):
```js
// TransformStream is available in environments such as CloudFlare workers.
// in Node.js, TransformStream needs to be explicitly imported from 'stream/web'
const { readable, writable } = new TransformStream()
pipeToWebWritable(app, {}, writable)
return new Response(readable)
```
### `renderToSimpleStream`
Renders input in streaming mode using a simple readable interface.
**Signature**
```ts
function renderToSimpleStream(
input: App | VNode,
context: SSRContext,
options: SimpleReadable
): SimpleReadable
interface SimpleReadable {
push(content: string | null): void
destroy(err: any): void
}
```
**Usage**
```js
let res = ''
renderToSimpleStream(
app,
{},
{
push(chunk) {
if (chunk === null) {
// done
console(`render complete: ${res}`)
} else {
res += chunk
}
},
destroy(err) {
// error encountered
}
}
)
```
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More