2025/2/8第一次更新

This commit is contained in:
爱吃咸鱼小猫咪
2025-02-08 18:50:38 +08:00
commit d7af560866
26519 changed files with 5046029 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
import type { Formatter } from '../logs/format';
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;
+143
View File
@@ -0,0 +1,143 @@
"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 = void 0;
const path_1 = __importDefault(require("path"));
const module_alias_1 = __importDefault(require("module-alias"));
const env_1 = require("./env");
const hbxPlugins = {
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',
};
function initModuleAlias() {
const compilerSfcPath = path_1.default.resolve(__dirname, '../../lib/@vue/compiler-sfc');
const serverRendererPath = require.resolve('@vue/server-renderer');
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-dom': require.resolve('@vue/compiler-dom'),
'@vue/compiler-sfc': compilerSfcPath,
'@vue/server-renderer': serverRendererPath,
'vue/compiler-sfc': compilerSfcPath,
'vue/server-renderer': 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, env_1.isInHBuilderX)()) {
// 又是为了复用 HBuilderX 的插件逻辑,硬编码映射
Object.keys(hbxPlugins).forEach((lang) => {
const realPath = path_1.default.resolve(process.env.UNI_HBUILDERX_PLUGINS, hbxPlugins[lang]);
module_alias_1.default.addAlias(lang,
// @ts-expect-error
() => {
try {
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 (process.env.UNI_PLATFORM === 'h5' ||
process.env.UNI_PLATFORM === 'web') {
// 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]) {
return path_1.default.resolve(process.env.UNI_HBUILDERX_PLUGINS, hbxPlugins[pkgName], packageJson);
}
}
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;
+7
View File
@@ -0,0 +1,7 @@
export declare const isInHBuilderX: () => boolean;
export declare const runByHBuilderX: () => boolean;
/**
* 增加 node_modules
*/
export declare function initModulePaths(): void;
export declare function fixBinaryPath(): void;
+79
View File
@@ -0,0 +1,79 @@
"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 path_1 = __importDefault(require("path"));
const module_1 = __importDefault(require("module"));
const uni_shared_1 = require("@dcloudio/uni-shared");
const resolve_1 = require("../resolve");
const utils_1 = require("../utils");
exports.isInHBuilderX = (0, uni_shared_1.once)(() => {
// 自动化测试传入了 HX_APP_ROOT(其实就是UNI_HBUILDERX_PLUGINS)
if (process.env.HX_APP_ROOT) {
process.env.UNI_HBUILDERX_PLUGINS = 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)
}
return false;
});
exports.runByHBuilderX = (0, uni_shared_1.once)(() => {
return (!!process.env.UNI_HBUILDERX_PLUGINS &&
(!!process.env.RUN_BY_HBUILDERX || !!process.env.HX_Version));
});
/**
* 增加 node_modules
*/
function initModulePaths() {
if (!(0, exports.isInHBuilderX)()) {
return;
}
const Module = module.constructor.length > 1 ? module.constructor : module_1.default;
const nodeModulesPath = path_1.default.resolve(process.env.UNI_CLI_CONTEXT, 'node_modules');
const oldNodeModulePaths = Module._nodeModulePaths;
Module._nodeModulePaths = function (from) {
const paths = oldNodeModulePaths.call(this, from);
if (!paths.includes(nodeModulesPath)) {
paths.push(nodeModulesPath);
}
return paths;
};
}
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, exports.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;
+4
View File
@@ -0,0 +1,4 @@
export { formatAtFilename } from './log';
export * from './env';
export { initModuleAlias, installHBuilderXPlugin, formatInstallHBuilderXPluginTips, } from './alias';
export declare function uniHBuilderXConsolePlugin(method?: string): import("vite").Plugin<any>;
+43
View File
@@ -0,0 +1,43 @@
"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.uniHBuilderXConsolePlugin = exports.formatInstallHBuilderXPluginTips = exports.installHBuilderXPlugin = exports.initModuleAlias = exports.formatAtFilename = void 0;
const path_1 = __importDefault(require("path"));
const utils_1 = require("../utils");
const console_1 = require("../vite/plugins/console");
var log_1 = require("./log");
Object.defineProperty(exports, "formatAtFilename", { enumerable: true, get: function () { return log_1.formatAtFilename; } });
__exportStar(require("./env"), exports);
var alias_1 = require("./alias");
Object.defineProperty(exports, "initModuleAlias", { enumerable: true, get: function () { return alias_1.initModuleAlias; } });
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__') {
return (0, console_1.uniConsolePlugin)({
method,
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;
+8
View File
@@ -0,0 +1,8 @@
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>;
+196
View File
@@ -0,0 +1,196 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
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 constants_1 = require("../constants");
const ast_1 = require("../vite/utils/ast");
const utils_2 = 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 (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 buildErrorMessage(err, args = [], includeStack = true) {
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];
}
}
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}`);
});
}
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_2.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)));
}
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`);
}