更新
This commit is contained in:
+202
@@ -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
@@ -0,0 +1,2 @@
|
||||
declare const _default: () => (import("vite").Plugin<any> | import("rollup").Plugin<any>[])[];
|
||||
export default _default;
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
"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 vueCompilerDom = __importStar(require("@vue/compiler-dom"));
|
||||
const uniCliShared = __importStar(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");
|
||||
exports.default = () => [
|
||||
...((0, uni_cli_shared_1.isEnableConsole)() ? [(0, uni_cli_shared_1.uniHBuilderXConsolePlugin)('uni.__f__')] : []),
|
||||
...(process.env.UNI_APP_X === 'true'
|
||||
? [
|
||||
(0, uni_cli_shared_1.uniDecryptUniModulesPlugin)(),
|
||||
(0, uni_cli_shared_1.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
@@ -0,0 +1,4 @@
|
||||
import type { Plugin, ResolvedConfig } from 'vite';
|
||||
export declare function createConfig(options: {
|
||||
resolvedConfig: ResolvedConfig | null;
|
||||
}): Plugin['config'];
|
||||
+113
@@ -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.json,hbx 工程可能没有,通过 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;
|
||||
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function createConfigureServer(): Plugin['configureServer'];
|
||||
Generated
Vendored
+20
@@ -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;
|
||||
Generated
Vendored
+9
@@ -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 {};
|
||||
Generated
Vendored
+80
@@ -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;
|
||||
Generated
Vendored
+5
@@ -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>;
|
||||
TongjiUniApp/node_modules/@dcloudio/uni-h5-vite/dist/plugin/configureServer/middlewares/timestamp.js
Generated
Vendored
+36
@@ -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;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { ViteDevServer } from 'vite';
|
||||
export declare const external: string[];
|
||||
export declare function initSSR(server: ViteDevServer): void;
|
||||
Generated
Vendored
+57
@@ -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;
|
||||
Generated
Vendored
+8
@@ -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;
|
||||
Generated
Vendored
+59
@@ -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;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { Plugin } from 'esbuild';
|
||||
export declare const JS_TYPES_RE: RegExp;
|
||||
export declare function esbuildPrePlugin(): Plugin;
|
||||
Generated
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.esbuildPrePlugin = exports.JS_TYPES_RE = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
exports.JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/;
|
||||
function esbuildPrePlugin() {
|
||||
return {
|
||||
name: 'uni:dep-scan',
|
||||
setup(build) {
|
||||
build.onLoad({ filter: exports.JS_TYPES_RE }, ({ path: id }) => {
|
||||
let ext = path_1.default.extname(id).slice(1);
|
||||
if (ext === 'mjs')
|
||||
ext = 'js';
|
||||
if (fs_1.default.existsSync(id)) {
|
||||
let contents = fs_1.default.readFileSync(id, 'utf-8');
|
||||
if (contents.includes('#endif')) {
|
||||
contents = (0, uni_cli_shared_1.preJs)(contents, id);
|
||||
}
|
||||
return {
|
||||
loader: ext,
|
||||
contents,
|
||||
};
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.esbuildPrePlugin = esbuildPrePlugin;
|
||||
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function createHandleHotUpdate(): Plugin['handleHotUpdate'];
|
||||
Generated
Vendored
+87
@@ -0,0 +1,87 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.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 { easyComOptions, refresh } = (0, uni_cli_shared_1.initEasycomsOnce)(inputDir, {
|
||||
dirs: (0, uni_cli_shared_1.resolveComponentsLibDirs)(),
|
||||
platform,
|
||||
isX: process.env.UNI_APP_X === 'true',
|
||||
});
|
||||
if (!equal({ autoscan: easycom.autoscan, custom: easycom.custom }, {
|
||||
autoscan: easyComOptions.autoscan,
|
||||
custom: easyComOptions.custom,
|
||||
})) {
|
||||
refresh();
|
||||
}
|
||||
}
|
||||
// 当pages.json,manifest.json发生变化时,作废pages.json.js缓存
|
||||
for (const file of invalidateFiles) {
|
||||
await invalidate(file, server.moduleGraph);
|
||||
}
|
||||
server.ws.send({
|
||||
type: 'full-reload',
|
||||
path: '*',
|
||||
});
|
||||
return [];
|
||||
};
|
||||
}
|
||||
exports.createHandleHotUpdate = createHandleHotUpdate;
|
||||
function equal(obj1, obj2) {
|
||||
return JSON.stringify(obj1) === JSON.stringify(obj2);
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import type { UniVitePlugin } from '@dcloudio/uni-cli-shared';
|
||||
export declare function uniH5Plugin(): UniVitePlugin;
|
||||
+25
@@ -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;
|
||||
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function createTransformIndexHtml(): Plugin['transformIndexHtml'];
|
||||
Generated
Vendored
+48
@@ -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;
|
||||
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
import type { NodeTransform } from '@vue/compiler-core';
|
||||
export declare const transformPageHead: NodeTransform;
|
||||
Generated
Vendored
+22
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -0,0 +1,2 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function uniInjectPlugin(): Plugin;
|
||||
+71
@@ -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
@@ -0,0 +1 @@
|
||||
export declare function uniMainJsPlugin(): import("vite").Plugin<any>;
|
||||
+50
@@ -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
@@ -0,0 +1,2 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function uniManifestJsonPlugin(): Plugin;
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniManifestJsonPlugin = void 0;
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const defaultRouter = {
|
||||
mode: 'hash',
|
||||
base: '/',
|
||||
assets: 'assets',
|
||||
routerBase: '/',
|
||||
};
|
||||
const defaultAsync = {
|
||||
loading: 'AsyncLoading',
|
||||
error: 'AsyncError',
|
||||
delay: 200,
|
||||
timeout: 60000,
|
||||
suspensible: true,
|
||||
};
|
||||
function uniManifestJsonPlugin() {
|
||||
return (0, uni_cli_shared_1.defineUniManifestJsonPlugin)((opts) => {
|
||||
let resolvedConfig;
|
||||
return {
|
||||
name: 'uni:h5-manifest-json',
|
||||
enforce: 'pre',
|
||||
configResolved(config) {
|
||||
defaultRouter.assets = config.build.assetsDir;
|
||||
resolvedConfig = config;
|
||||
},
|
||||
transform(code, id) {
|
||||
if (!opts.filter(id)) {
|
||||
return;
|
||||
}
|
||||
const manifest = (0, uni_cli_shared_1.parseJson)(code, false, id);
|
||||
const { debug } = manifest;
|
||||
const h5 = (0, uni_cli_shared_1.getPlatformManifestJson)(manifest, 'h5');
|
||||
const router = {
|
||||
...defaultRouter,
|
||||
...{ base: resolvedConfig.base },
|
||||
...((h5 && h5.router) || {}),
|
||||
};
|
||||
if (!router.base) {
|
||||
router.base = '/';
|
||||
}
|
||||
/**
|
||||
* ssr时base和访问域名不一致导致跳到错误链接,其实应该区分server和client的部署路径,后续有需求可以加上
|
||||
*/
|
||||
router.routerBase = new URL(router.base, 'http://localhost').pathname;
|
||||
const async = { ...defaultAsync, ...((h5 && h5.async) || {}) };
|
||||
const networkTimeout = (0, uni_cli_shared_1.normalizeNetworkTimeout)(manifest.networkTimeout);
|
||||
const sdkConfigs = (h5 && h5.sdkConfigs) || {};
|
||||
const tempTencentMapKey = sdkConfigs.maps &&
|
||||
sdkConfigs.maps.tencent &&
|
||||
sdkConfigs.maps.tencent.key;
|
||||
const tempQQMapKey = sdkConfigs.maps && sdkConfigs.maps.qqmap && sdkConfigs.maps.qqmap.key;
|
||||
const qqMapKey = tempTencentMapKey || tempQQMapKey;
|
||||
const bMapKey = sdkConfigs.maps && sdkConfigs.maps.bmap && sdkConfigs.maps.bmap.key;
|
||||
const googleMapKey = sdkConfigs.maps &&
|
||||
sdkConfigs.maps.google &&
|
||||
sdkConfigs.maps.google.key;
|
||||
const aMapKey = sdkConfigs.maps && sdkConfigs.maps.amap && sdkConfigs.maps.amap.key;
|
||||
const aMapSecurityJsCode = sdkConfigs.maps &&
|
||||
sdkConfigs.maps.amap &&
|
||||
sdkConfigs.maps.amap.securityJsCode;
|
||||
const aMapServiceHost = sdkConfigs.maps &&
|
||||
sdkConfigs.maps.amap &&
|
||||
sdkConfigs.maps.amap.serviceHost;
|
||||
let locale = manifest.locale;
|
||||
locale = locale && locale.toUpperCase() !== 'AUTO' ? locale : '';
|
||||
const i18nOptions = (0, uni_cli_shared_1.initI18nOptions)(process.env.UNI_PLATFORM, process.env.UNI_INPUT_DIR, false, false);
|
||||
const fallbackLocale = (i18nOptions && i18nOptions.locale) || '';
|
||||
const vueType = process.env.UNI_APP_X === 'true' ? 'uvue' : 'nvue';
|
||||
const flexDirection = (process.env.UNI_APP_X === 'true'
|
||||
? manifest['uni-app-x'] && manifest['uni-app-x']['flex-direction']
|
||||
: manifest['app'] &&
|
||||
manifest['app'].nvue &&
|
||||
manifest['app'].nvue['flex-direction']) || 'column';
|
||||
return {
|
||||
code: `export const appId = ${JSON.stringify(manifest.appid || '')}
|
||||
export const appName = ${JSON.stringify(manifest.name || '')}
|
||||
export const appVersion = ${JSON.stringify(manifest.versionName || '')}
|
||||
export const appVersionCode = ${JSON.stringify(manifest.versionCode || '')}
|
||||
|
||||
export const debug = ${!!debug}
|
||||
export const ${vueType} = ${JSON.stringify({
|
||||
'flex-direction': flexDirection,
|
||||
})}
|
||||
export const networkTimeout = ${JSON.stringify(networkTimeout)}
|
||||
// h5
|
||||
export const router = ${JSON.stringify(router)}
|
||||
export const async = ${JSON.stringify(async)}
|
||||
export const qqMapKey = ${JSON.stringify(qqMapKey)}
|
||||
export const bMapKey = ${JSON.stringify(bMapKey)}
|
||||
export const googleMapKey = ${JSON.stringify(googleMapKey)}
|
||||
export const aMapKey = ${JSON.stringify(aMapKey)}
|
||||
export const aMapSecurityJsCode = ${JSON.stringify(aMapSecurityJsCode)}
|
||||
export const aMapServiceHost = ${JSON.stringify(aMapServiceHost)}
|
||||
export const sdkConfigs = ${JSON.stringify(sdkConfigs)}
|
||||
export const locale = '${locale}'
|
||||
export const fallbackLocale = '${fallbackLocale}'
|
||||
export const darkmode = ${h5.darkmode || 'false'}
|
||||
export const themeConfig = ${JSON.stringify((0, uni_cli_shared_1.normalizeThemeConfigOnce)(h5))}
|
||||
`,
|
||||
map: { mappings: '' },
|
||||
};
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
exports.uniManifestJsonPlugin = uniManifestJsonPlugin;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function uniPagesJsonPlugin(): Plugin;
|
||||
+261
@@ -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, id), 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 += `const ${name} = defineAsyncComponent(()=>import('./${windowConfig.path}').then(com=>setupWindow(com.default || com,${windowNames[name]})))\n`;
|
||||
defineLayoutComponentsCode += `${globalName}.__uniConfig.${name}.component = ${name}\n`;
|
||||
}
|
||||
});
|
||||
return {
|
||||
importLayoutComponentsCode,
|
||||
defineLayoutComponentsCode,
|
||||
};
|
||||
}
|
||||
function generatePageDefineCode(pageOptions) {
|
||||
let pagePathWithExtname = (0, uni_cli_shared_1.normalizePagePath)(pageOptions.path, 'h5');
|
||||
if (!pagePathWithExtname) {
|
||||
// 不存在时,仍引用,此时编译会报错文件不存在
|
||||
pagePathWithExtname = pageOptions.path + '.vue';
|
||||
}
|
||||
const pageIdent = (0, uni_cli_shared_1.normalizeIdentifier)(pageOptions.path);
|
||||
return `const ${pageIdent}Loader = ()=>import('./${pagePathWithExtname}').then(com => setupPage(com.default || com))
|
||||
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
@@ -0,0 +1,2 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function uniPostVuePlugin(): Plugin;
|
||||
+48
@@ -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
@@ -0,0 +1,2 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function uniRenderjsPlugin(): Plugin;
|
||||
+47
@@ -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
@@ -0,0 +1,2 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function uniResolveIdPlugin(): Plugin;
|
||||
+51
@@ -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
@@ -0,0 +1,2 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function uniSetupPlugin(): Plugin;
|
||||
+34
@@ -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
@@ -0,0 +1,2 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function uniPostSourceMapPlugin(): Plugin;
|
||||
+57
@@ -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
@@ -0,0 +1,2 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function uniSSRPlugin(): Plugin;
|
||||
+67
@@ -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
@@ -0,0 +1 @@
|
||||
export declare const ownerModuleName = "@dcloudio/uni-h5";
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ownerModuleName = void 0;
|
||||
exports.ownerModuleName = '@dcloudio/uni-h5';
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import type { ConfigEnv, UserConfig } from 'vite';
|
||||
export declare function createDefine(command: ConfigEnv['command'], config: UserConfig): UserConfig['define'];
|
||||
+18
@@ -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
@@ -0,0 +1,3 @@
|
||||
export * from './ssr';
|
||||
export * from './features';
|
||||
export * from './constants';
|
||||
+19
@@ -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
@@ -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
@@ -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;
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
[
|
||||
"$emit",
|
||||
"$off",
|
||||
"$on",
|
||||
"$once",
|
||||
"__f__",
|
||||
"addInterceptor",
|
||||
"addPhoneContact",
|
||||
"arrayBufferToBase64",
|
||||
"base64ToArrayBuffer",
|
||||
"canIUse",
|
||||
"canvasGetImageData",
|
||||
"canvasPutImageData",
|
||||
"canvasToTempFilePath",
|
||||
"chooseFile",
|
||||
"chooseImage",
|
||||
"chooseLocation",
|
||||
"chooseVideo",
|
||||
"clearStorage",
|
||||
"clearStorageSync",
|
||||
"closePreviewImage",
|
||||
"closeSocket",
|
||||
"connectSocket",
|
||||
"createAnimation",
|
||||
"createCameraContext",
|
||||
"createCanvasContext",
|
||||
"createInnerAudioContext",
|
||||
"createIntersectionObserver",
|
||||
"createLivePlayerContext",
|
||||
"createMapContext",
|
||||
"createMediaQueryObserver",
|
||||
"createSelectorQuery",
|
||||
"createVideoContext",
|
||||
"downloadFile",
|
||||
"getAppBaseInfo",
|
||||
"getClipboardData",
|
||||
"getDeviceInfo",
|
||||
"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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -0,0 +1 @@
|
||||
[https://dcloud.io/license/uni-app.html](https://dcloud.io/license/uni-app.html)
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"name": "@dcloudio/uni-h5-vite",
|
||||
"version": "3.0.0-4060620250520001",
|
||||
"description": "uni-h5-vite",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"files": [
|
||||
"dist",
|
||||
"lib"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/dcloudio/uni-app.git",
|
||||
"directory": "packages/uni-h5-vite"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"gitHead": "33e807d66e1fe47e2ee08ad9c59247e37b8884da",
|
||||
"dependencies": {
|
||||
"@rollup/pluginutils": "^5.0.5",
|
||||
"@vue/compiler-dom": "3.4.21",
|
||||
"@vue/compiler-sfc": "3.4.21",
|
||||
"@vue/server-renderer": "3.4.21",
|
||||
"@vue/shared": "3.4.21",
|
||||
"debug": "^4.3.3",
|
||||
"fs-extra": "^10.0.0",
|
||||
"mime": "^3.0.0",
|
||||
"module-alias": "^2.2.2",
|
||||
"@dcloudio/uni-cli-shared": "3.0.0-4060620250520001",
|
||||
"@dcloudio/uni-shared": "3.0.0-4060620250520001"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/debug": "^4.1.7",
|
||||
"@types/fs-extra": "^9.0.13",
|
||||
"@types/mime": "^2.0.3",
|
||||
"@types/module-alias": "^2.0.4",
|
||||
"@types/resolve": "^1.20.2",
|
||||
"@vue/compiler-core": "3.4.21",
|
||||
"esbuild": "^0.20.1",
|
||||
"vue": "3.4.21"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user