前端 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
@@ -0,0 +1,8 @@
import type { Formatter } from '../logs/format';
export declare function resolveWebVaporPackage(packageName: string): string;
export declare function initWebVaporAliases(): void;
export declare function normalizeUniAppXVaporEnv(): void;
export declare function initModuleAlias(): void;
export declare function installHBuilderXPlugin(plugin: string): void;
export declare const moduleAliasFormatter: Formatter;
export declare function formatInstallHBuilderXPluginTips(lang: string, preprocessor: string): string;
+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;
+4
View File
@@ -0,0 +1,4 @@
export { isInHBuilderX } from './utils';
export declare const runByHBuilderX: () => boolean;
export declare function initModulePaths(): void;
export declare function fixBinaryPath(): void;
+167
View File
@@ -0,0 +1,167 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fixBinaryPath = exports.initModulePaths = exports.runByHBuilderX = exports.isInHBuilderX = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const module_1 = __importDefault(require("module"));
const url_1 = require("url");
const uni_shared_1 = require("@dcloudio/uni-shared");
const resolve_1 = require("../resolve");
const utils_1 = require("../utils");
const utils_2 = require("./utils");
var utils_3 = require("./utils");
Object.defineProperty(exports, "isInHBuilderX", { enumerable: true, get: function () { return utils_3.isInHBuilderX; } });
exports.runByHBuilderX = (0, uni_shared_1.once)(() => {
return ((!!process.env.HX_PLUGIN_PATHS || !!process.env.UNI_HBUILDERX_PLUGINS) &&
(!!process.env.RUN_BY_HBUILDERX || !!process.env.HX_Version));
});
/**
* 增加 node_modules
*/
const initializedModulePaths = new Set();
function getPackageName(specifier) {
if (!specifier ||
specifier.startsWith('.') ||
specifier.startsWith('/') ||
specifier.startsWith('\\') ||
specifier.startsWith('#') ||
specifier.includes(':') ||
/[\\%?#]/.test(specifier)) {
return;
}
const segments = specifier.split('/');
if (segments.some((segment) => !segment || segment === '.' || segment === '..') ||
(specifier.startsWith('@') &&
(segments.length < 2 || segments[0].length === 1))) {
return;
}
const packageName = specifier.startsWith('@')
? segments.slice(0, 2).join('/')
: segments[0];
return packageName;
}
function canFallbackToNodeModules(specifier, error, nodeModulesPath) {
const code = error?.code;
if (code !== 'ERR_MODULE_NOT_FOUND') {
return false;
}
const packageName = getPackageName(specifier);
return (!!packageName && fs_1.default.existsSync(path_1.default.resolve(nodeModulesPath, packageName)));
}
function initModulePaths() {
if (!(0, utils_2.isInHBuilderX)()) {
return;
}
const nodeModulesPath = path_1.default.resolve(process.env.UNI_CLI_CONTEXT, 'node_modules');
if (initializedModulePaths.has(nodeModulesPath)) {
return;
}
const parentURL = (0, url_1.pathToFileURL)(path_1.default.resolve(process.env.UNI_CLI_CONTEXT, 'package.json')).href;
const moduleApi = module_1.default;
const Module = module.constructor.length > 1 ? module.constructor : module_1.default;
const oldNodeModulePaths = Module._nodeModulePaths;
Module._nodeModulePaths = function (from) {
const paths = oldNodeModulePaths.call(this, from);
if (!paths.includes(nodeModulesPath)) {
paths.push(nodeModulesPath);
}
return paths;
};
if (moduleApi.registerHooks) {
moduleApi.registerHooks({
resolve(specifier, context, nextResolve) {
try {
return nextResolve(specifier, context);
}
catch (error) {
if (!canFallbackToNodeModules(specifier, error, nodeModulesPath)) {
throw error;
}
return nextResolve(specifier, { ...context, parentURL });
}
},
});
initializedModulePaths.add(nodeModulesPath);
return;
}
// Node 的 ESM 解析不会使用 _nodeModulePaths,需要单独回退到 HBuilderX 内置依赖。
const register = moduleApi.register;
if (register) {
const nodeModulesURL = (0, url_1.pathToFileURL)(nodeModulesPath + path_1.default.sep).href;
const loader = `
import { existsSync } from 'node:fs'
const parentURL = ${JSON.stringify(parentURL)}
const nodeModulesURL = ${JSON.stringify(nodeModulesURL)}
export async function resolve(specifier, context, nextResolve) {
try {
return await nextResolve(specifier, context)
} catch (error) {
if (
error?.code !== 'ERR_MODULE_NOT_FOUND' ||
!specifier ||
specifier.startsWith('.') ||
specifier.startsWith('/') ||
specifier.startsWith('\\\\') ||
specifier.startsWith('#') ||
specifier.includes(':') ||
/[\\\\%?#]/.test(specifier)
) {
throw error
}
const segments = specifier.split('/')
if (
segments.some(
(segment) => !segment || segment === '.' || segment === '..'
) ||
(specifier.startsWith('@') &&
(segments.length < 2 || segments[0].length === 1))
) {
throw error
}
const packageName = specifier.startsWith('@')
? segments.slice(0, 2).join('/')
: segments[0]
if (!existsSync(new URL(packageName + '/', nodeModulesURL))) {
throw error
}
return nextResolve(specifier, { ...context, parentURL })
}
}
`;
register(`data:text/javascript,${encodeURIComponent(loader)}`, (0, url_1.pathToFileURL)(process.env.UNI_CLI_CONTEXT + path_1.default.sep));
}
initializedModulePaths.add(nodeModulesPath);
}
exports.initModulePaths = initModulePaths;
function resolveEsbuildModule(name) {
try {
return path_1.default.dirname(require.resolve(name + '/package.json', {
paths: [path_1.default.dirname((0, resolve_1.resolveBuiltIn)('esbuild/package.json'))],
}));
}
catch (e) { }
return '';
}
function fixBinaryPath() {
// cli 工程在 HBuilderX 中运行
if (!(0, utils_2.isInHBuilderX)() && (0, exports.runByHBuilderX)()) {
if (utils_1.isWindows) {
const win64 = resolveEsbuildModule('esbuild-windows-64');
if (win64) {
process.env.ESBUILD_BINARY_PATH = path_1.default.join(win64, 'esbuild.exe');
}
}
else {
const arm64 = resolveEsbuildModule('esbuild-darwin-arm64');
if (arm64) {
process.env.ESBUILD_BINARY_PATH = path_1.default.join(arm64, 'bin/esbuild');
}
}
}
}
exports.fixBinaryPath = fixBinaryPath;
@@ -0,0 +1,6 @@
export { formatAtFilename, createErrorWithBlockFlag } from './log';
export * from './env';
export { resolveHBuilderXPluginPath } from './pluginPaths';
export { initWebVaporAliases, resolveWebVaporPackage, initModuleAlias, normalizeUniAppXVaporEnv, installHBuilderXPlugin, formatInstallHBuilderXPluginTips, } from './alias';
export declare function uniHBuilderXConsolePlugin(method?: string): import("vite").Plugin<any>;
export declare function isEnableConsole(): boolean;
+69
View File
@@ -0,0 +1,69 @@
"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);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isEnableConsole = exports.uniHBuilderXConsolePlugin = exports.formatInstallHBuilderXPluginTips = exports.installHBuilderXPlugin = exports.normalizeUniAppXVaporEnv = exports.initModuleAlias = exports.resolveWebVaporPackage = exports.initWebVaporAliases = exports.resolveHBuilderXPluginPath = exports.createErrorWithBlockFlag = exports.formatAtFilename = void 0;
const path_1 = __importDefault(require("path"));
const utils_1 = require("../utils");
const console_1 = require("../vite/plugins/console");
const workers_1 = require("../workers");
var log_1 = require("./log");
Object.defineProperty(exports, "formatAtFilename", { enumerable: true, get: function () { return log_1.formatAtFilename; } });
Object.defineProperty(exports, "createErrorWithBlockFlag", { enumerable: true, get: function () { return log_1.createErrorWithBlockFlag; } });
__exportStar(require("./env"), exports);
var pluginPaths_1 = require("./pluginPaths");
Object.defineProperty(exports, "resolveHBuilderXPluginPath", { enumerable: true, get: function () { return pluginPaths_1.resolveHBuilderXPluginPath; } });
var alias_1 = require("./alias");
Object.defineProperty(exports, "initWebVaporAliases", { enumerable: true, get: function () { return alias_1.initWebVaporAliases; } });
Object.defineProperty(exports, "resolveWebVaporPackage", { enumerable: true, get: function () { return alias_1.resolveWebVaporPackage; } });
Object.defineProperty(exports, "initModuleAlias", { enumerable: true, get: function () { return alias_1.initModuleAlias; } });
Object.defineProperty(exports, "normalizeUniAppXVaporEnv", { enumerable: true, get: function () { return alias_1.normalizeUniAppXVaporEnv; } });
Object.defineProperty(exports, "installHBuilderXPlugin", { enumerable: true, get: function () { return alias_1.installHBuilderXPlugin; } });
Object.defineProperty(exports, "formatInstallHBuilderXPluginTips", { enumerable: true, get: function () { return alias_1.formatInstallHBuilderXPluginTips; } });
function uniHBuilderXConsolePlugin(method = '__f__') {
const exclude = [];
if (process.env.UNI_APP_X === 'true') {
const workersDirs = (0, workers_1.resolveWorkersDir)(process.env.UNI_INPUT_DIR);
if (workersDirs.length) {
// 排除workers目录
for (const workersDir of workersDirs) {
exclude.push((0, utils_1.pathToGlob)(path_1.default.join(process.env.UNI_INPUT_DIR, workersDir), '**/*'));
}
}
}
return (0, console_1.uniConsolePlugin)({
method,
exclude,
filename(filename) {
filename = path_1.default.relative(process.env.UNI_INPUT_DIR, filename);
if (filename.startsWith('.') || path_1.default.isAbsolute(filename)) {
return '';
}
return (0, utils_1.normalizePath)(filename);
},
});
}
exports.uniHBuilderXConsolePlugin = uniHBuilderXConsolePlugin;
function isEnableConsole() {
return !!((process.env.NODE_ENV === 'development' ||
process.env.NODE_ENV === 'test') &&
process.env.UNI_SOCKET_HOSTS &&
process.env.UNI_SOCKET_PORT &&
process.env.UNI_SOCKET_ID);
}
exports.isEnableConsole = isEnableConsole;
+13
View File
@@ -0,0 +1,13 @@
import type { LogErrorOptions } from 'vite';
import type { Formatter } from '../logs/format';
export declare function formatAtFilename(filename: string, line?: number, column?: number): string;
export declare const h5ServeFormatter: Formatter;
export declare const removeInfoFormatter: Formatter;
export declare const removeWarnFormatter: Formatter;
export declare const removeDuplicatePluginFormatter: Formatter;
export declare const errorFormatter: Formatter<LogErrorOptions>;
interface ErrorWithBlockFlag extends Error {
__errorBlocked: true;
}
export declare function createErrorWithBlockFlag(msg: string): ErrorWithBlockFlag;
export {};
+268
View File
@@ -0,0 +1,268 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createErrorWithBlockFlag = exports.errorFormatter = exports.removeDuplicatePluginFormatter = exports.removeWarnFormatter = exports.removeInfoFormatter = exports.h5ServeFormatter = exports.formatAtFilename = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const picocolors_1 = __importDefault(require("picocolors"));
const compiler_core_1 = require("@vue/compiler-core");
const shared_1 = require("@vue/shared");
const utils_1 = require("../utils");
const utils_2 = require("./utils");
const constants_1 = require("../constants");
const ast_1 = require("../vite/utils/ast");
const utils_3 = require("../vite/plugins/vitejs/utils");
const SIGNAL_H5_LOCAL = ' ➜ Local:';
const SIGNAL_H5_NETWORK = ' ➜ Network:';
const networkLogs = [];
const ZERO_WIDTH_CHAR = {
NOTE: '',
WARNING: '\u200B',
ERROR: '\u200C',
backup0: '\u200D', // 标记换行
backup1: '\u200E',
backup2: '\u200F',
backup3: '\uFEFF',
};
function overridedConsole(name, oldFn, char) {
console[name] = function (...args) {
oldFn.apply(this, args.map((arg) => {
let item;
if ((0, utils_2.isInHBuilderX)() && typeof arg === 'string' && arg.includes('\n')) {
arg = arg
.split('\n')
.map((line) => `${char}${line}${char}`)
.join('\n');
}
if (typeof arg !== 'object') {
item = `${char}${arg}${char}`;
}
else {
item = `${char}${JSON.stringify(arg)}${char}`;
}
return item;
}));
};
}
if (typeof console !== 'undefined') {
overridedConsole('warn', console.log, ZERO_WIDTH_CHAR.WARNING);
// overridedConsole('error', console.error, ZERO_WIDTH_CHAR.ERROR)
}
function formatAtFilename(filename, line, column) {
filename = filename.replace('\x00', '').split('?')[0];
const file = process.env.UNI_INPUT_DIR
? path_1.default.relative(process.env.UNI_INPUT_DIR, filename)
: filename;
return `at ${picocolors_1.default.cyan((0, utils_1.normalizePath)(file === 'pages-json-uts' ? 'pages.json' : file) +
':' +
(line || 1) +
':' +
(column || 0))}`;
}
exports.formatAtFilename = formatAtFilename;
exports.h5ServeFormatter = {
test(msg) {
return msg.includes(SIGNAL_H5_LOCAL) || msg.includes(SIGNAL_H5_NETWORK);
},
format(msg) {
if (msg.includes(SIGNAL_H5_NETWORK)) {
networkLogs.push(msg.replace('➜ ', '*'));
process.nextTick(() => {
if (networkLogs.length) {
// 延迟打印所有 network,仅最后一个 network 替换 ➜ 为 -,通知 hbx
const len = networkLogs.length - 1;
networkLogs[len] = networkLogs[len].replace('* Network', '- Network');
console.log(networkLogs.join('\n'));
networkLogs.length = 0;
}
});
return '';
}
if (msg.includes(SIGNAL_H5_LOCAL)) {
return msg.replace('➜ ', '-');
}
return msg.replace('➜ ', '*');
},
};
const REMOVED_MSGS = [
'build started...',
(msg) => {
return /built in [0-9]+ms\./.test(msg);
},
'watching for file changes...',
];
exports.removeInfoFormatter = {
test(msg) {
return !!REMOVED_MSGS.find((m) => ((0, shared_1.isString)(m) ? msg.includes(m) : m(msg)));
},
format() {
return '';
},
};
const REMOVED_WARN_MSGS = [];
exports.removeWarnFormatter = {
test(msg) {
return !!REMOVED_WARN_MSGS.find((m) => msg.includes(m));
},
format() {
return '';
},
};
exports.removeDuplicatePluginFormatter = {
test() {
return true;
},
format(msg) {
// [plugin:vite:vue] [plugin vite:vue]
// 正则匹配获取第一个插件名称,然后移除 [plugin vite:vue]
const pluginName = msg.match(/\[plugin\s([^\]]+)\]/)?.[1];
if (pluginName) {
return msg.replace(`[plugin ${pluginName}]`, '');
}
return msg;
},
};
exports.errorFormatter = {
test(_, opts) {
return !!(opts && opts.error);
},
format(_, opts) {
return buildErrorMessage(opts.error, [], false);
},
};
function createErrorWithBlockFlag(msg) {
const error = new Error(msg);
error.__errorBlocked = true;
return error;
}
exports.createErrorWithBlockFlag = createErrorWithBlockFlag;
let shouldAddErrorBlock = null;
const VITE_ROLLUP_FAILED_TO_RESOLVE_IMPORT_RE = /\[vite\]: Rollup failed to resolve import "([^"]+)" from "([^"]+)"/;
const CANNOT_FIND_MODULE_RE = /Cannot find module '([^']+)' from '([^']+)'/;
function buildErrorMessage(err, args = [], includeStack = true) {
if (err.customPrint) {
err.customPrint();
return '';
}
if (VITE_ROLLUP_FAILED_TO_RESOLVE_IMPORT_RE.test(err.message)) {
const [, importPath, fromPath] = err.message.match(VITE_ROLLUP_FAILED_TO_RESOLVE_IMPORT_RE) || [];
err.message = `Could not resolve "${importPath}" from "${fromPath}"`;
err.id = fromPath;
}
if (CANNOT_FIND_MODULE_RE.test(err.message)) {
const [, modulePath, fromPath] = err.message.match(CANNOT_FIND_MODULE_RE) || [];
// 清理模块路径和来源路径,移除查询参数等
const cleanModulePath = modulePath.split('?')[0];
const cleanFromPath = fromPath.split('?')[0];
const relativeFromPath = toRelativePath(cleanFromPath);
// 构建更友好的错误消息
err.id = cleanFromPath;
err.message = `Cannot find module "${cleanModulePath}" from "${relativeFromPath}"`;
}
// 移除 from 后面的内容
// 主要是处理:Could not resolve "./static/logo1.png" from "../../../../../../Users/xxx/HBuilderProjects/test-x/pages/index/index.uvue?vue&type=script&lang.uts"
if (err.id && err.message.startsWith('Could not resolve ')) {
err.message = err.message.split(' from ')[0];
}
if (err.plugin) {
// 避免出现这样的错误:[plugin:vite:vue] [plugin vite:vue]
if (err.message.startsWith(`[plugin ${err.plugin}]`)) {
let msg = err.message.replace(`[plugin ${err.plugin}]`, '');
if (err.loc) {
// [plugin:vite:vue] pages/index/index.vue (2:12): v-on="" is not supported
const locStr = `(${err.loc.line}:${err.loc.column}):`;
if (msg.includes(locStr)) {
msg = msg.split(locStr)[1].trim();
}
}
args.push(`${picocolors_1.default.magenta('[plugin:' + err.plugin + ']')} ${picocolors_1.default.red(msg)}`);
}
else {
const otherMsgs = [];
if (err.message.includes(': [plugin ')) {
const messages = err.message.split(': [plugin ');
err.message = messages[0];
messages.slice(1).forEach((msg) => {
otherMsgs.push(`[plugin:${msg}`);
});
}
if (err.loc) {
// [plugin:vite:vue] pages/index/index.vue (2:12): v-on="" is not supported
const locStr = `(${err.loc.line}:${err.loc.column}):`;
if (err.message.includes(locStr)) {
err.message = err.message.split(locStr)[1].trim();
}
}
args.push(`${picocolors_1.default.magenta('[plugin:' + err.plugin + ']')} ${picocolors_1.default.red(err.message)}`);
args.push(...otherMsgs);
if (err.loc &&
err.hook === 'transform' &&
err.plugin === 'rollup-plugin-dynamic-import-variables' &&
err.id &&
constants_1.EXTNAME_VUE_RE.test(err.id)) {
try {
const ast = (0, ast_1.parseVue)(fs_1.default.readFileSync(err.id, 'utf8'), []);
const scriptNode = ast.children.find((node) => node.type === compiler_core_1.NodeTypes.ELEMENT && node.tag === 'script');
if (scriptNode) {
const scriptLoc = scriptNode.loc;
args.push(picocolors_1.default.yellow(pad((0, utils_3.generateCodeFrame)(scriptLoc.source, err.loc))));
// correct error location
err.loc.line = scriptLoc.start.line + err.loc.line - 1;
}
}
catch (e) { }
}
}
}
else {
args.push(picocolors_1.default.red(err.message));
}
if (err.id) {
args.push(formatAtFilename(err.id, err.loc?.line, err.loc?.column));
}
if (err.frame) {
args.push(picocolors_1.default.yellow(pad(err.frame)));
}
if (includeStack && err.stack) {
args.push(pad(cleanStack(err.stack)));
}
if (shouldAddErrorBlock === null) {
shouldAddErrorBlock = // 目前仅限 x 的 app 平台
process.env.UNI_APP_X === 'true' &&
(process.env.UNI_UTS_PLATFORM === 'app-android' ||
process.env.UNI_UTS_PLATFORM === 'app-ios' ||
process.env.UNI_UTS_PLATFORM === 'app-harmony');
}
if (shouldAddErrorBlock) {
if (!err.__errorBlocked) {
args[0] = constants_1.SPECIAL_CHARS.ERROR_BLOCK + args[0];
args[args.length - 1] = args[args.length - 1] + constants_1.SPECIAL_CHARS.ERROR_BLOCK;
}
}
return args.join('\n');
}
function cleanStack(stack) {
return stack
.split(/\n/g)
.filter((l) => /^\s*at/.test(l))
.join('\n');
}
const splitRE = /\r?\n/;
function pad(source, n = 2) {
const lines = source.split(splitRE);
return lines.map((l) => ` `.repeat(n) + l).join(`\n`);
}
function toRelativePath(filePath) {
if (!filePath || !process.env.UNI_INPUT_DIR) {
return filePath;
}
try {
return path_1.default.relative(process.env.UNI_INPUT_DIR, filePath);
}
catch (e) {
// 转换失败时返回原路径
return filePath;
}
}
@@ -0,0 +1 @@
export declare function resolveHBuilderXPluginPath(pluginName: string, ...subpaths: string[]): string | undefined;
@@ -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.resolveHBuilderXPluginPath = void 0;
const path_1 = __importDefault(require("path"));
const uni_shared_1 = require("@dcloudio/uni-shared");
const getHBuilderXPluginPaths = (0, uni_shared_1.once)(() => {
const raw = process.env.HX_PLUGIN_PATHS;
if (!raw) {
return;
}
const pluginPaths = JSON.parse(raw);
if (!pluginPaths ||
typeof pluginPaths !== 'object' ||
Array.isArray(pluginPaths)) {
throw new Error('Invalid HX_PLUGIN_PATHS');
}
return pluginPaths;
});
function resolveHBuilderXPluginPath(pluginName, ...subpaths) {
const pluginPaths = getHBuilderXPluginPaths();
const mappedPath = pluginPaths?.[pluginName];
// 缺少 key 时使用旧目录;空字符串表示显式未配置,不回退。
const pluginPath = mappedPath !== undefined
? mappedPath
: process.env.UNI_HBUILDERX_PLUGINS
? path_1.default.resolve(process.env.UNI_HBUILDERX_PLUGINS, pluginName)
: undefined;
return pluginPath ? path_1.default.resolve(pluginPath, ...subpaths) : undefined;
}
exports.resolveHBuilderXPluginPath = resolveHBuilderXPluginPath;
@@ -0,0 +1 @@
export declare const isInHBuilderX: () => boolean;
+32
View File
@@ -0,0 +1,32 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isInHBuilderX = void 0;
const path_1 = __importDefault(require("path"));
const uni_shared_1 = require("@dcloudio/uni-shared");
exports.isInHBuilderX = (0, uni_shared_1.once)(() => {
// 启动端应在加载编译器前传入工程类型,CLI 工程不能因 IDE 插件路径而使用内置环境。
if (process.env.UNI_PROJECT_TYPE === 'cli') {
return false;
}
// 未传工程类型时,沿用引入 HX_PLUGIN_PATHS 之前的识别及根目录初始化逻辑。
// 自动化测试传入了 HX_APP_ROOT(其实就是UNI_HBUILDERX_PLUGINS)
if (process.env.HX_APP_ROOT) {
process.env.UNI_HBUILDERX_PLUGINS = path_1.default.resolve(process.env.HX_APP_ROOT, 'plugins');
return true;
}
try {
const { name } = require(path_1.default.resolve(process.cwd(), '../about/package.json'));
if (name === 'about') {
process.env.UNI_HBUILDERX_PLUGINS = path_1.default.resolve(process.cwd(), '..');
return true;
}
}
catch (e) {
// console.error(e)
}
// 插件路径不代表工程类型;V 的独立插件布局由启动端显式传入 hbuilder。
return process.env.UNI_PROJECT_TYPE === 'hbuilder';
});