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

This commit is contained in:
zhiqui
2026-11-15 15:09:37 +08:00
parent 513b53672e
commit ea7c2529e9
24104 changed files with 3667749 additions and 0 deletions
+365
View File
@@ -0,0 +1,365 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatInstallHBuilderXPluginTips = exports.moduleAliasFormatter = exports.installHBuilderXPlugin = exports.initModuleAlias = exports.normalizeUniAppXVaporEnv = exports.initWebVaporAliases = exports.resolveWebVaporPackage = void 0;
// 注意:该文件尽可能少依赖其他文件,否则可能会导致还没有alias的时候,就加载了目标模块
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const module_alias_1 = __importDefault(require("module-alias"));
const utils_1 = require("./utils");
const pluginPaths_1 = require("./pluginPaths");
const hbxPlugins = {
// 普通 uni-app 的 SFC 外部类型解析通过此别名加载 TypeScript,按需依赖 compile-typescript。
// uni-app x 编译链通过 resolveUniTypeScript 使用 uni-uts-v1 自带的 TypeScript,
// 不走此别名,也不依赖 compile-typescript;注册别名本身不会加载该插件。
typescript: ['compile-typescript', 'node_modules/typescript'],
less: ['compile-less', 'node_modules/less'],
sass: ['compile-dart-sass', 'node_modules/sass'],
stylus: ['compile-stylus', 'node_modules/stylus'],
pug: ['compile-pug-cli', 'node_modules/pug'],
};
const commonVuePackages = [
'@vue/compiler-core',
'@vue/compiler-dom',
'@vue/compiler-sfc',
'@vue/shared',
];
const vaporVuePackages = [...commonVuePackages, '@vue/compiler-vapor'];
const webVaporVuePackages = [
...commonVuePackages,
'@vue/compiler-ssr',
'@vue/compiler-vapor',
'@vue/server-renderer',
];
function addVaporVuePackageAliases(vueDir, packages) {
const aliases = {};
packages.forEach((pkg) => {
aliases[pkg] = path_1.default.resolve(vueDir, pkg.slice(pkg.lastIndexOf('/') + 1));
});
module_alias_1.default.addAliases(aliases);
}
function resolveWebVaporPackage(packageName) {
return path_1.default.resolve(__dirname, '../../lib/dom2/web', packageName);
}
exports.resolveWebVaporPackage = resolveWebVaporPackage;
function resolveWebVaporPluginVue() {
return resolveWebVaporPackage('@vitejs/plugin-vue/dist/index.cjs');
}
function initWebVaporAliases() {
const webDir = resolveWebVaporPackage('');
const webVueDir = path_1.default.join(webDir, '@vue');
addVaporVuePackageAliases(webVueDir, webVaporVuePackages);
module_alias_1.default.addAliases({
'@vitejs/plugin-vue': resolveWebVaporPluginVue(),
'@dcloudio/compiler-vapor-web': path_1.default.join(webVueDir, 'compiler-vapor-web'),
'vue/compiler-sfc': path_1.default.join(webVueDir, 'compiler-sfc'),
'vue/server-renderer': path_1.default.join(webVueDir, 'server-renderer'),
});
}
exports.initWebVaporAliases = initWebVaporAliases;
function addAppVaporAliases(libDir) {
const appVueDir = path_1.default.resolve(libDir, 'dom2', 'app', '@vue');
addVaporVuePackageAliases(appVueDir, vaporVuePackages);
module_alias_1.default.addAliases({
'@vitejs/plugin-vue': path_1.default.resolve(libDir, 'dom2', 'app', '@vitejs', 'plugin-vue'),
'@dcloudio/compiler-vapor-dom2': path_1.default.join(appVueDir, 'compiler-vapor-dom2'),
});
}
function addNonVaporVuePackageAliases(libDir, compilerSfcPath, serverRendererPath) {
module_alias_1.default.addAliases({
'@vue/shared': require.resolve('@vue/shared'),
'@vue/shared/dist/shared.esm-bundler.js': require.resolve('@vue/shared/dist/shared.esm-bundler.js'),
'@vue/compiler-core': path_1.default.resolve(libDir, '@vue/compiler-core'),
'@vue/compiler-dom': require.resolve('@vue/compiler-dom'),
'@vue/compiler-sfc': compilerSfcPath,
'@vue/server-renderer': serverRendererPath,
'vue/compiler-sfc': compilerSfcPath,
'vue/server-renderer': serverRendererPath,
});
}
function isWebOrMpPlatform(platform) {
return platform === 'h5' || platform === 'web' || platform?.startsWith('mp-');
}
function isWebPlatform(platform) {
return platform === 'h5' || platform === 'web';
}
function hasWebVaporConfig() {
// 框架自身生成 dist-x-vapor 时没有用户项目目录,通过内部构建标记绕过配置文件检查。
if (process.env.UNI_APP_X_VAPOR_BUILD === 'true') {
return true;
}
// HBuilderX/CLI 会在加载框架前传入项目根目录。
const inputDir = process.env.UNI_INPUT_DIR;
return !!inputDir && fs_1.default.existsSync(path_1.default.resolve(inputDir, '.vapor'));
}
function resolveUniCliPlatform() {
const entry = process.argv[1];
if (!entry || !['uni', 'uni.js'].includes(path_1.default.basename(entry))) {
return;
}
const args = process.argv.slice(2);
for (let index = 0; index < args.length; index++) {
const arg = args[index];
if (arg === '--') {
break;
}
if (arg === '-p' || arg === '--platform') {
const platform = args[index + 1];
if (platform && !platform.startsWith('-')) {
return platform;
}
}
else if (arg.startsWith('-p=') || arg.startsWith('--platform=')) {
const platform = arg.slice(arg.indexOf('=') + 1);
if (platform) {
return platform;
}
}
}
return 'h5';
}
// 在归一化前记录外部开关,避免将初始化生成的 DOM2 状态误认为外部配置。
const externalDom2 = process.env.UNI_APP_X_DOM2 === 'true';
function normalizeUniAppXVaporEnv() {
// App 使用 UNI_APP_X_VAPOR 作为对外开关;Web 还支持 .vapor 和 DOM2 环境变量。
const utsPlatform = process.env.UNI_UTS_PLATFORM;
const uniPlatform = process.env.UNI_PLATFORM;
const cliPlatform = resolveUniCliPlatform();
const platform = cliPlatform || utsPlatform || uniPlatform;
const webVaporConfigured = isWebPlatform(platform) && (externalDom2 || hasWebVaporConfig());
// HBuilderX dev 不会预先注入 UNI_APP_X,因此这里需要同步补齐 uni-app x 环境标记。
const isWebVapor = webVaporConfigured;
if (isWebVapor) {
process.env.UNI_APP_X = 'true';
// Web Vapor 固定使用新样式隔离,在加载插件前统一首次编译、HMR 和 CSS 处理规则。
process.env.UNI_APP_STYLE_ISOLATION_VERSION = '2';
}
if (process.env.UNI_APP_X_VAPOR === 'true' || isWebVapor) {
process.env.UNI_APP_X_DOM2 = 'true';
}
else if (process.env.UNI_APP_X_VAPOR === 'false') {
delete process.env.UNI_APP_X_DOM2;
}
// alias 初始化早于 CLI 环境初始化,优先读取 CLI 参数,否则使用预置的平台环境变量。
// 小程序仍关闭 Vapor,Web 平台使用独立的 Web Vapor 产物。
const shouldDisableVapor = cliPlatform
? isWebOrMpPlatform(cliPlatform) && !isWebVapor
: (isWebOrMpPlatform(utsPlatform) || isWebOrMpPlatform(uniPlatform)) &&
!isWebVapor;
if (shouldDisableVapor) {
delete process.env.UNI_APP_X_DOM2;
}
// 将平台归一化后的实际状态同步回对外开关。
if (isWebVapor) {
process.env.UNI_APP_X_VAPOR = 'true';
process.env.UNI_APP_X_DOM2 = 'true';
}
if (process.env.UNI_APP_X_DOM2 === 'true') {
process.env.UNI_APP_X_VAPOR = 'true';
}
else {
delete process.env.UNI_APP_X_DOM2;
delete process.env.UNI_APP_X_VAPOR;
delete process.env.UNI_APP_X_DOM2_DYNAMIC;
delete process.env.UNI_APP_X_VAPOR_RENDER_TARGET;
}
}
exports.normalizeUniAppXVaporEnv = normalizeUniAppXVaporEnv;
function initModuleAlias() {
normalizeUniAppXVaporEnv();
const libDir = path_1.default.resolve(__dirname, '../../lib');
const compilerSfcPath = path_1.default.resolve(libDir, '@vue/compiler-sfc');
const serverRendererPath = require.resolve('@vue/server-renderer');
if (process.env.UNI_OUTPUT_DIR) {
const baseOutDir = path_1.default.basename(process.env.UNI_OUTPUT_DIR);
process.env.UNI_APP_X_CACHE_DIR =
process.env.UNI_APP_X_CACHE_DIR ||
path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../cache/.' + baseOutDir);
}
// 对路径进行兼容
if (!process.env.UNI_APP_X_DOM2_CPP_DIR &&
process.env.UNI_APP_HARMONY_DOM2_CPP_DIR) {
process.env.UNI_APP_X_DOM2_CPP_DIR =
process.env.UNI_APP_HARMONY_DOM2_CPP_DIR;
}
const platform = resolveUniCliPlatform() ||
process.env.UNI_UTS_PLATFORM ||
process.env.UNI_PLATFORM;
const webVapor = process.env.UNI_APP_X_VAPOR === 'true' && isWebPlatform(platform);
if (webVapor) {
initWebVaporAliases();
}
else if (process.env.UNI_APP_X_DOM2 === 'true') {
if (process.env.UNI_OUTPUT_DIR &&
(process.env.UNI_PLATFORM === 'app' ||
process.env.UNI_PLATFORM === 'app-plus' ||
process.env.UNI_PLATFORM === 'app-harmony')) {
if (!process.env.UNI_APP_X_DOM2_CPP_DIR) {
let baseDir = '';
const isAndroid = process.env.UNI_APP_PLATFORM === 'android';
const isIOS = process.env.UNI_APP_PLATFORM === 'ios';
if (process.env.NODE_ENV !== 'development' && (isAndroid || isIOS)) {
baseDir = path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '.uniappx', isAndroid ? 'android' : 'ios');
}
else {
baseDir =
process.env.UNI_PLATFORM === 'app-harmony'
? process.env.UNI_OUTPUT_DIR
: process.env.UNI_APP_X_CACHE_DIR || process.env.UNI_OUTPUT_DIR;
}
process.env.UNI_APP_X_DOM2_CPP_DIR = path_1.default.resolve(baseDir, 'cpp');
process.env.UNI_APP_X_DOM2_SO_DIR = path_1.default.resolve(baseDir, 'so');
}
if (!process.env.UNI_APP_X_DOM2_KT_DIR) {
if (process.env.NODE_ENV !== 'development') {
process.env.UNI_APP_X_DOM2_KT_DIR = path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '.uniappx/android', 'src');
}
else {
process.env.UNI_APP_X_DOM2_KT_DIR = path_1.default.resolve(process.env.UNI_APP_X_CACHE_DIR ||
path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../.cache'), 'src');
}
}
}
if (process.env.UNI_APP_PLATFORM ||
process.env.UNI_PLATFORM === 'app-harmony') {
if (!process.env.UNI_APP_X_VAPOR_RENDER_TARGET) {
// 默认 app 平台使用 bytecode 目标
process.env.UNI_APP_X_VAPOR_RENDER_TARGET = 'bytecode';
}
if (process.env.UNI_APP_X_VAPOR_RENDER_TARGET?.includes('bytecode')) {
process.env.UNI_APP_X_DOM2_DYNAMIC = 'true';
}
// 如果是 ext-api 目标,强制使用 nativecode 目标
if (process.env.UNI_COMPILE_TARGET === 'ext-api') {
delete process.env.UNI_APP_X_DOM2_DYNAMIC;
}
}
}
if (process.env.UNI_APP_X_DOM2 === 'true' && !webVapor) {
addAppVaporAliases(libDir);
}
else if (!webVapor) {
addNonVaporVuePackageAliases(libDir, compilerSfcPath, serverRendererPath);
}
if (process.env.VITEST) {
module_alias_1.default.addAliases({
vue: '@dcloudio/uni-h5-vue',
'vue/package.json': '@dcloudio/uni-h5-vue/package.json',
});
}
if ((0, utils_1.isInHBuilderX)()) {
// 又是为了复用 HBuilderX 的插件逻辑,硬编码映射
Object.keys(hbxPlugins).forEach((lang) => {
const [pluginName, subpath] = hbxPlugins[lang];
const realPath = (0, pluginPaths_1.resolveHBuilderXPluginPath)(pluginName, subpath);
module_alias_1.default.addAlias(lang,
// @ts-expect-error
() => {
try {
if (!realPath) {
throw new Error(`HBuilder plugin "${pluginName}" is not found`);
}
require.resolve(realPath);
}
catch (e) {
const msg = exports.moduleAliasFormatter.format(`Preprocessor dependency "${lang}" not found. Did you install it?`);
console.error(msg);
process.exit(0);
}
return realPath;
});
});
// web 平台用了 vite 内置 css 插件,该插件会加载预编译器如scss、less等,需要转向到 HBuilderX 的对应编译器插件
if (isWebPlatform(process.env.UNI_PLATFORM)) {
// https://github.com/vitejs/vite/blob/main/packages/vite/src/node/packages.ts#L92
// 拦截预编译器
const join = path_1.default.join;
path_1.default.join = function (...paths) {
if (paths.length === 4) {
// path.join(basedir, 'node_modules', pkgName, 'package.json')
// const basedir = paths[0]
const nodeModules = paths[1]; // = node_modules
const pkgName = paths[2];
const packageJson = paths[3]; // = package.json
if (nodeModules === 'node_modules' &&
packageJson === 'package.json' &&
hbxPlugins[pkgName]) {
const [pluginName, subpath] = hbxPlugins[pkgName];
return ((0, pluginPaths_1.resolveHBuilderXPluginPath)(pluginName, subpath, packageJson) ||
join(...paths));
}
}
return join(...paths);
};
// https://github.com/vitejs/vite/blob/892916d040a035edde1add93c192e0b0c5c9dd86/packages/vite/src/node/plugins/css.ts#L1481
// const oldSync = resovle.sync
// resovle.sync = (id: string, opts?: SyncOpts) => {
// if ((hbxPlugins as any)[id]) {
// return path.resolve(
// process.env.UNI_HBUILDERX_PLUGINS,
// hbxPlugins[id as keyof typeof hbxPlugins]
// )
// }
// return oldSync(id, opts)
// }
}
}
}
exports.initModuleAlias = initModuleAlias;
function supportAutoInstallPlugin() {
return !!process.env.HX_Version;
}
function installHBuilderXPlugin(plugin) {
if (!supportAutoInstallPlugin()) {
return;
}
return console.error(`%HXRunUniAPPPluginName%${plugin}%HXRunUniAPPPluginName%`);
}
exports.installHBuilderXPlugin = installHBuilderXPlugin;
const installPreprocessorTips = {};
exports.moduleAliasFormatter = {
test(msg) {
return msg.includes('Preprocessor dependency');
},
format(msg) {
let lang = '';
let preprocessor = '';
if (msg.includes(`"pug"`)) {
lang = 'pug';
preprocessor = 'compile-pug-cli';
}
else if (msg.includes(`"sass"`)) {
lang = 'sass';
preprocessor = 'compile-dart-sass';
}
else if (msg.includes(`"less"`)) {
lang = 'less';
preprocessor = 'compile-less';
}
else if (msg.includes('"stylus"')) {
lang = 'stylus';
preprocessor = 'compile-stylus';
}
else if (msg.includes('"typescript"')) {
lang = 'typescript';
preprocessor = 'compile-typescript';
}
if (lang) {
// 仅提醒一次
if (installPreprocessorTips[lang]) {
return '';
}
installPreprocessorTips[lang] = true;
installHBuilderXPlugin(preprocessor);
return formatInstallHBuilderXPluginTips(lang, preprocessor);
}
return msg;
},
};
function formatInstallHBuilderXPluginTips(lang, preprocessor) {
return `预编译器错误:代码使用了${lang}语言,但未安装相应的编译器插件,${supportAutoInstallPlugin() ? '正在从' : '请前往'}插件市场安装该插件:
https://ext.dcloud.net.cn/plugin?name=${preprocessor}`;
}
exports.formatInstallHBuilderXPluginTips = formatInstallHBuilderXPluginTips;