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
+28
View File
@@ -0,0 +1,28 @@
/// <reference types="node" />
import { type Plugin } from 'vite';
import type { OutputOptions } from 'rollup';
export declare function uniCssPlugin(): Plugin;
/**
* converts the source filepath of the asset to the output filename based on the assetFileNames option. \
* this function imitates the behavior of rollup.js. \
* https://rollupjs.org/guide/en/#outputassetfilenames
*
* @example
* ```ts
* const content = Buffer.from('text');
* const fileName = assetFileNamesToFileName(
* 'assets/[name].[hash][extname]',
* '/path/to/file.txt',
* getAssetHash(content),
* content
* )
* // fileName: 'assets/file.982d9e3e.txt'
* ```
*
* @param assetFileNames filename pattern. e.g. `'assets/[name].[hash][extname]'`
* @param file filepath of the asset
* @param contentHash hash of the asset. used for `'[hash]'` placeholder
* @param content content of the asset. passed to `assetFileNames` if `assetFileNames` is a function
* @returns output filename
*/
export declare function assetFileNamesToFileName(assetFileNames: Exclude<OutputOptions['assetFileNames'], undefined>, file: string, contentHash: string, content: string | Buffer): string;
+205
View File
@@ -0,0 +1,205 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.assetFileNamesToFileName = exports.uniCssPlugin = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const vite_1 = require("vite");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const shared_1 = require("@vue/shared");
function isCombineBuiltInCss(config) {
return config.command === 'build' && config.build.cssCodeSplit;
}
function uniCssPlugin() {
let resolvedConfig;
let file = '';
let fileName = '';
return {
name: 'uni:h5-css',
apply: 'build',
enforce: 'pre',
configResolved(config) {
resolvedConfig = config;
file = path_1.default.join(process.env.UNI_INPUT_DIR, 'uni.css');
if (process.env.UNI_COMPILE_TARGET === 'uni_modules') {
(0, uni_cli_shared_1.injectCssPlugin)(config, {
createUrlReplacer: uni_cli_shared_1.createEncryptCssUrlReplacer,
});
(0, uni_cli_shared_1.injectCssPostPlugin)(config, (0, uni_cli_shared_1.cssPostPlugin)(config, {
platform: process.env.UNI_PLATFORM,
preserveModules: true,
chunkCssFilename(id) {
if ((0, uni_cli_shared_1.isVueSfcFile)(id)) {
return ((0, uni_cli_shared_1.removeExt)((0, vite_1.normalizePath)(path_1.default.relative(process.env.UNI_INPUT_DIR, id))) + '.css');
}
},
chunkCssCode(_filename, cssCode) {
return cssCode;
},
}));
(0, uni_cli_shared_1.injectAssetPlugin)(config);
}
},
transform(code, id) {
id = (0, vite_1.normalizePath)(id);
if (id.endsWith(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'shadow.css')) {
const url = (0, uni_cli_shared_1.createShadowImageUrl)(0, 'grey');
return {
code: code +
`
@keyframes shadow-preload {
0% {
background-image: url(${url});
}
100% {
background-image: url(${url});
}
}
`,
map: { mappings: '' },
};
}
else if (id.endsWith(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'pageHead.css')) {
return {
code: code +
`
.uni-page-head-shadow-grey::after {
background-image: url('${(0, uni_cli_shared_1.createShadowImageUrl)(0, 'grey')}');
}
.uni-page-head-shadow-blue::after {
background-image: url('${(0, uni_cli_shared_1.createShadowImageUrl)(0, 'blue')}');
}
.uni-page-head-shadow-green::after {
background-image: url('${(0, uni_cli_shared_1.createShadowImageUrl)(0, 'green')}');
}
.uni-page-head-shadow-orange::after {
background-image: url('${(0, uni_cli_shared_1.createShadowImageUrl)(0, 'orange')}');
}
.uni-page-head-shadow-red::after {
background-image: url('${(0, uni_cli_shared_1.createShadowImageUrl)(0, 'red')}');
}
.uni-page-head-shadow-yellow::after {
background-image: url('${(0, uni_cli_shared_1.createShadowImageUrl)(0, 'yellow')}');
}
`,
map: { mappings: '' },
};
}
},
async generateBundle() {
if (!isCombineBuiltInCss(resolvedConfig) || !uni_cli_shared_1.buildInCssSet.size) {
return;
}
// 生成框架css(需要排序,避免生成不一样的内容)
const content = await (0, uni_cli_shared_1.minifyCSS)(generateBuiltInCssCode([...uni_cli_shared_1.buildInCssSet].sort()), resolvedConfig);
// 'Buffer' only refers to a type, but is being used as a value here
const contentHash = (0, uni_cli_shared_1.getAssetHash)(Buffer.from(content, 'utf-8'));
const assetFileNames = path_1.default.posix.join(resolvedConfig.build.assetsDir, '[name].[hash][extname]');
fileName = assetFileNamesToFileName(assetFileNames, file, contentHash, content);
const name = (0, vite_1.normalizePath)(path_1.default.relative(resolvedConfig.root, file));
this.emitFile({
name,
fileName,
type: 'asset',
source: content,
});
},
transformIndexHtml: {
order: 'post',
handler() {
if (!fileName) {
return;
}
// 追加框架css
return [
{
tag: 'link',
attrs: {
rel: 'stylesheet',
href: toPublicPath(fileName, resolvedConfig),
},
injectTo: 'head-prepend',
},
];
},
},
};
}
exports.uniCssPlugin = uniCssPlugin;
function toPublicPath(filename, config) {
return (0, uni_cli_shared_1.isExternalUrl)(filename) ? filename : config.base + filename;
}
function generateBuiltInCssCode(cssImports) {
return cssImports
.map((cssImport) => fs_1.default.readFileSync((0, uni_cli_shared_1.resolveBuiltIn)(cssImport), 'utf8'))
.join('\n');
}
/**
* converts the source filepath of the asset to the output filename based on the assetFileNames option. \
* this function imitates the behavior of rollup.js. \
* https://rollupjs.org/guide/en/#outputassetfilenames
*
* @example
* ```ts
* const content = Buffer.from('text');
* const fileName = assetFileNamesToFileName(
* 'assets/[name].[hash][extname]',
* '/path/to/file.txt',
* getAssetHash(content),
* content
* )
* // fileName: 'assets/file.982d9e3e.txt'
* ```
*
* @param assetFileNames filename pattern. e.g. `'assets/[name].[hash][extname]'`
* @param file filepath of the asset
* @param contentHash hash of the asset. used for `'[hash]'` placeholder
* @param content content of the asset. passed to `assetFileNames` if `assetFileNames` is a function
* @returns output filename
*/
function assetFileNamesToFileName(assetFileNames, file, contentHash, content) {
const basename = path_1.default.basename(file);
// placeholders for `assetFileNames`
// `hash` is slightly different from the rollup's one
const extname = path_1.default.extname(basename);
const ext = extname.slice(1);
const name = basename.slice(0, -extname.length);
const hash = contentHash;
if ((0, shared_1.isFunction)(assetFileNames)) {
assetFileNames = assetFileNames({
name: file,
originalFileName: file,
source: content,
type: 'asset',
});
if (!(0, shared_1.isString)(assetFileNames)) {
throw new TypeError('assetFileNames must return a string');
}
}
else if (!(0, shared_1.isString)(assetFileNames)) {
throw new TypeError('assetFileNames must be a string or a function');
}
const fileName = assetFileNames.replace(/\[\w+\]/g, (placeholder) => {
switch (placeholder) {
case '[ext]':
return ext;
case '[extname]':
return extname;
case '[hash]':
return hash;
case '[name]':
return name;
}
throw new Error(`invalid placeholder ${placeholder} in assetFileNames "${assetFileNames}"`);
});
return fileName;
}
exports.assetFileNamesToFileName = assetFileNamesToFileName;
+8
View File
@@ -0,0 +1,8 @@
import type { Plugin } from 'vite';
import { type FilterPattern } from '@rollup/pluginutils';
interface UniEasycomPluginOptions {
include?: FilterPattern;
exclude?: FilterPattern;
}
export declare function uniEasycomPlugin(options: UniEasycomPluginOptions): Plugin;
export {};
+133
View File
@@ -0,0 +1,133 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniEasycomPlugin = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const pluginutils_1 = require("@rollup/pluginutils");
const shared_1 = require("@vue/shared");
const uni_shared_1 = require("@dcloudio/uni-shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const H5_COMPONENTS_PATH = '@dcloudio/uni-h5';
const xBaseComponents = ['slider', 'switch'];
const baseComponents = [
'audio',
'button',
'canvas',
'checkbox',
'checkbox-group',
'editor',
'form',
'icon',
'image',
'input',
'label',
'movable-area',
'movable-view',
'navigator',
'picker-view',
'picker-view-column',
'progress',
'radio',
'radio-group',
'resize-sensor',
'refresher',
'rich-text',
'scroll-view',
'slider',
'swiper',
'swiper-item',
'switch',
'text',
'textarea',
'view',
'list-view',
'list-item',
'sticky-section',
'sticky-header',
];
let componentDepsCss;
function uniEasycomPlugin(options) {
const filter = (0, pluginutils_1.createFilter)(options.include, options.exclude);
let needCombineBuiltInCss = false;
componentDepsCss = (0, uni_cli_shared_1.COMPONENT_DEPS_CSS)(process.env.UNI_APP_X === 'true');
return {
name: 'uni:h5-easycom',
configResolved(config) {
needCombineBuiltInCss = (0, uni_cli_shared_1.isCombineBuiltInCss)(config);
},
transform(code, id) {
if (!filter(id)) {
return;
}
const { filename } = (0, uni_cli_shared_1.parseVueRequest)(id);
if (!uni_cli_shared_1.EXTNAME_VUE_TEMPLATE.includes(path_1.default.extname(filename))) {
return;
}
if (!code.includes('_resolveComponent')) {
return;
}
let i = 0;
const importDeclarations = [];
code = code.replace(/_resolveComponent\("(.+?)"(, true)?\)/g, (str, name) => {
if (name && !name.startsWith('_')) {
if ((0, uni_shared_1.isBuiltInComponent)(name)) {
name = name.replace(uni_shared_1.COMPONENT_PREFIX, '');
const local = `__syscom_${i++}`;
if (needCombineBuiltInCss) {
// 发行模式下,应该将内置组件css输出到入口css中
resolveBuiltInCssImport(name).forEach((cssImport) => uni_cli_shared_1.buildInCssSet.add(cssImport));
return (0, uni_cli_shared_1.addImportDeclaration)(importDeclarations, local, H5_COMPONENTS_PATH, (0, shared_1.capitalize)((0, shared_1.camelize)(name)));
}
return addBuiltInImportDeclaration(importDeclarations, local, name);
}
const source = (0, uni_cli_shared_1.matchEasycom)(name);
if (source) {
const isHelpers = source.includes('?uni_helpers');
if (isHelpers) {
const cssFilename = path_1.default.join(process.env.UNI_MODULES_ENCRYPT_CACHE_DIR, path_1.default.relative(process.env.UNI_INPUT_DIR, source.replace('?uni_helpers', '/components/' + name + '/' + name + '.css')));
if (fs_extra_1.default.existsSync(cssFilename)) {
importDeclarations.push(`import "${(0, uni_cli_shared_1.normalizePath)(cssFilename)}";`);
}
}
// 处理easycom组件优先级
return (0, uni_cli_shared_1.genResolveEasycomCode)(importDeclarations, str, (0, uni_cli_shared_1.addImportDeclaration)(importDeclarations, `__easycom_${i++}`, source, isHelpers ? (0, shared_1.capitalize)((0, shared_1.camelize)(name)) : ''));
}
}
return str;
});
if (importDeclarations.length) {
code = importDeclarations.join('') + code;
}
return {
code,
map: null,
};
},
};
}
exports.uniEasycomPlugin = uniEasycomPlugin;
function resolveBuiltInCssImport(name) {
const cssImports = [];
if (baseComponents.includes(name)) {
const isX = process.env.UNI_APP_X === 'true';
if (isX && xBaseComponents.includes(name)) {
cssImports.push(uni_cli_shared_1.X_BASE_COMPONENTS_STYLE_PATH + name + '.css');
}
else {
cssImports.push(uni_cli_shared_1.BASE_COMPONENTS_STYLE_PATH + name + '.css');
}
}
else {
cssImports.push(uni_cli_shared_1.H5_COMPONENTS_STYLE_PATH + name + '.css');
}
const deps = componentDepsCss[name];
deps && deps.forEach((dep) => cssImports.push(dep));
return cssImports;
}
function addBuiltInImportDeclaration(importDeclarations, local, name) {
resolveBuiltInCssImport(name).forEach((cssImport) => importDeclarations.push(`import '${cssImport}';`));
return (0, uni_cli_shared_1.addImportDeclaration)(importDeclarations, local, H5_COMPONENTS_PATH, (0, shared_1.capitalize)((0, shared_1.camelize)(name)));
}
+2
View File
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniInjectPlugin(): Plugin;
+71
View File
@@ -0,0 +1,71 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniInjectPlugin = void 0;
const path_1 = __importDefault(require("path"));
const shared_1 = require("@vue/shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const apiJson = require(path_1.default.resolve(__dirname, process.env.UNI_APP_X === 'true'
? '../../lib/api.x.json'
: '../../lib/api.json'));
const uniInjectPluginOptions = {
exclude: [...uni_cli_shared_1.COMMON_EXCLUDE],
'uni.': [
'@dcloudio/uni-h5',
((method) => apiJson.includes(method)),
],
// 兼容 wx 对象
'wx.': [
'@dcloudio/uni-h5',
((method) => apiJson.includes(method)),
],
getApp: ['@dcloudio/uni-h5', 'getApp'],
getCurrentPages: ['@dcloudio/uni-h5', 'getCurrentPages'],
UniServiceJSBridge: ['@dcloudio/uni-h5', 'UniServiceJSBridge'],
UniViewJSBridge: ['@dcloudio/uni-h5', 'UniViewJSBridge'],
};
function uniInjectPlugin() {
let resolvedConfig;
const apiDepsCss = (0, uni_cli_shared_1.API_DEPS_CSS)(process.env.UNI_APP_X === 'true');
const callback = function (imports, mod) {
const styles = mod[0] === '@dcloudio/uni-h5' &&
apiDepsCss[mod[1]];
if (!styles) {
return;
}
styles.forEach((style) => {
if ((0, uni_cli_shared_1.isCombineBuiltInCss)(resolvedConfig)) {
uni_cli_shared_1.buildInCssSet.add(style);
}
else {
if (!imports.has(style)) {
imports.set(style, `import '${style}';`);
}
}
});
};
let injectPlugin;
return {
name: 'uni:h5-inject',
apply: 'build',
enforce: 'post',
configResolved(config) {
resolvedConfig = config;
const enableTreeShaking = (0, uni_cli_shared_1.isEnableTreeShaking)((0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR));
if (!enableTreeShaking) {
// 不启用摇树优化,移除 wx、uni 等 API 配置
delete uniInjectPluginOptions['wx.'];
delete uniInjectPluginOptions['uni.'];
}
injectPlugin = (0, uni_cli_shared_1.uniViteInjectPlugin)('uni:h5-inject', (0, shared_1.extend)(uniInjectPluginOptions, {
callback,
}));
},
transform(code, id) {
return injectPlugin.transform.call(this, code, id);
},
};
}
exports.uniInjectPlugin = uniInjectPlugin;
+1
View File
@@ -0,0 +1 @@
export declare function uniMainJsPlugin(): import("vite").Plugin<any>;
+50
View File
@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniMainJsPlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../utils");
function uniMainJsPlugin() {
return (0, uni_cli_shared_1.defineUniMainJsPlugin)((opts) => {
let runSSR = false;
return {
name: 'uni:h5-main-js',
enforce: 'pre',
configResolved(config) {
runSSR =
(0, uni_cli_shared_1.isSsr)(config.command, config) || (0, utils_1.isSsrManifest)(config.command, config);
},
transform(code, id, options) {
if (opts.filter(id)) {
if (!runSSR) {
code = code.includes('createSSRApp')
? createApp(code)
: createLegacyApp(code);
}
else {
code = (0, utils_1.isSSR)(options)
? createSSRServerApp(code)
: createSSRClientApp(code);
}
code = `import './${uni_cli_shared_1.PAGES_JSON_JS}';${code}`;
return {
code,
map: this.getCombinedSourcemap(),
};
}
},
};
});
}
exports.uniMainJsPlugin = uniMainJsPlugin;
function createApp(code) {
return `import { plugin as __plugin } from '@dcloudio/uni-h5';${code.replace('createSSRApp', 'createVueApp as createSSRApp')};createApp().app.use(__plugin).mount("#app");`;
}
function createLegacyApp(code) {
return `import { plugin as __plugin } from '@dcloudio/uni-h5';function createApp(rootComponent,rootProps){return createVueApp(rootComponent, rootProps).use(__plugin)};${code.replace('createApp', 'createVueApp')}`;
}
function createSSRClientApp(code) {
return `import { plugin as __plugin } from '@dcloudio/uni-h5';import { UNI_SSR, UNI_SSR_STORE } from '@dcloudio/uni-shared';${code};\n// @ts-ignore\nconst { app: __app, store: __store } = createApp();__app.use(__plugin);__store && window[UNI_SSR] && window[UNI_SSR][UNI_SSR_STORE] && __store.replaceState(window[UNI_SSR][UNI_SSR_STORE]);__app.router.isReady().then(() => __app.mount("#app"));`;
}
function createSSRServerApp(code) {
return code;
}
+2
View File
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniManifestJsonPlugin(): Plugin;
+111
View File
@@ -0,0 +1,111 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniManifestJsonPlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const defaultRouter = {
mode: 'hash',
base: '/',
assets: 'assets',
routerBase: '/',
};
const defaultAsync = {
loading: 'AsyncLoading',
error: 'AsyncError',
delay: 200,
timeout: 60000,
suspensible: true,
};
function uniManifestJsonPlugin() {
return (0, uni_cli_shared_1.defineUniManifestJsonPlugin)((opts) => {
let resolvedConfig;
return {
name: 'uni:h5-manifest-json',
enforce: 'pre',
configResolved(config) {
defaultRouter.assets = config.build.assetsDir;
resolvedConfig = config;
},
transform(code, id) {
if (!opts.filter(id)) {
return;
}
const manifest = (0, uni_cli_shared_1.parseJson)(code);
const { debug } = manifest;
const h5 = (0, uni_cli_shared_1.getPlatformManifestJson)(manifest, 'h5');
const router = {
...defaultRouter,
...{ base: resolvedConfig.base },
...((h5 && h5.router) || {}),
};
if (!router.base) {
router.base = '/';
}
/**
* ssr时base和访问域名不一致导致跳到错误链接,其实应该区分server和client的部署路径,后续有需求可以加上
*/
router.routerBase = new URL(router.base, 'http://localhost').pathname;
const async = { ...defaultAsync, ...((h5 && h5.async) || {}) };
const networkTimeout = (0, uni_cli_shared_1.normalizeNetworkTimeout)(manifest.networkTimeout);
const sdkConfigs = (h5 && h5.sdkConfigs) || {};
const tempTencentMapKey = sdkConfigs.maps &&
sdkConfigs.maps.tencent &&
sdkConfigs.maps.tencent.key;
const tempQQMapKey = sdkConfigs.maps && sdkConfigs.maps.qqmap && sdkConfigs.maps.qqmap.key;
const qqMapKey = tempTencentMapKey || tempQQMapKey;
const bMapKey = sdkConfigs.maps && sdkConfigs.maps.bmap && sdkConfigs.maps.bmap.key;
const googleMapKey = sdkConfigs.maps &&
sdkConfigs.maps.google &&
sdkConfigs.maps.google.key;
const aMapKey = sdkConfigs.maps && sdkConfigs.maps.amap && sdkConfigs.maps.amap.key;
const aMapSecurityJsCode = sdkConfigs.maps &&
sdkConfigs.maps.amap &&
sdkConfigs.maps.amap.securityJsCode;
const aMapServiceHost = sdkConfigs.maps &&
sdkConfigs.maps.amap &&
sdkConfigs.maps.amap.serviceHost;
let locale = manifest.locale;
locale = locale && locale.toUpperCase() !== 'AUTO' ? locale : '';
const i18nOptions = (0, uni_cli_shared_1.initI18nOptions)(process.env.UNI_PLATFORM, process.env.UNI_INPUT_DIR, false, false);
const fallbackLocale = (i18nOptions && i18nOptions.locale) || '';
const vueType = process.env.UNI_APP_X === 'true' ? 'uvue' : 'nvue';
const flexDirection = (process.env.UNI_APP_X === 'true'
? manifest['uni-app-x'] && manifest['uni-app-x']['flex-direction']
: manifest['app'] &&
manifest['app'].nvue &&
manifest['app'].nvue['flex-direction']) || 'column';
const platformConfig = manifest[process.env.UNI_PLATFORM === 'app'
? 'app-plus'
: process.env.UNI_PLATFORM] || {};
return {
code: `export const appId = ${JSON.stringify(manifest.appid || '')}
export const appName = ${JSON.stringify(manifest.name || '')}
export const appVersion = ${JSON.stringify(manifest.versionName || '')}
export const appVersionCode = ${JSON.stringify(manifest.versionCode || '')}
export const debug = ${!!debug}
export const ${vueType} = ${JSON.stringify({
'flex-direction': flexDirection,
})}
export const networkTimeout = ${JSON.stringify(networkTimeout)}
// h5
export const router = ${JSON.stringify(router)}
export const async = ${JSON.stringify(async)}
export const qqMapKey = ${JSON.stringify(qqMapKey)}
export const bMapKey = ${JSON.stringify(bMapKey)}
export const googleMapKey = ${JSON.stringify(googleMapKey)}
export const aMapKey = ${JSON.stringify(aMapKey)}
export const aMapSecurityJsCode = ${JSON.stringify(aMapSecurityJsCode)}
export const aMapServiceHost = ${JSON.stringify(aMapServiceHost)}
export const sdkConfigs = ${JSON.stringify(sdkConfigs)}
export const locale = '${locale}'
export const fallbackLocale = '${fallbackLocale}'
export const darkmode = ${platformConfig.darkmode || 'false'}
export const themeConfig = ${JSON.stringify((0, uni_cli_shared_1.normalizeThemeConfigOnce)(platformConfig))}
`,
map: { mappings: '' },
};
},
};
});
}
exports.uniManifestJsonPlugin = uniManifestJsonPlugin;
+2
View File
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniPagesJsonPlugin(): Plugin;
+261
View File
@@ -0,0 +1,261 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniPagesJsonPlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../utils");
function uniPagesJsonPlugin() {
return (0, uni_cli_shared_1.defineUniPagesJsonPlugin)((opts) => {
return {
name: 'uni:h5-pages-json',
enforce: 'pre',
transform(code, id, opt) {
if (opts.filter(id)) {
const { resolvedConfig } = opts;
const ssr = (0, utils_1.isSSR)(opt);
if (process.env.UNI_APP_X === 'true') {
// 调整换行符,确保 parseTree 的loc正确
code = code.replace(/\r\n/g, '\n');
try {
(0, uni_cli_shared_1.checkPagesJson)((0, uni_cli_shared_1.preUVueJson)(code), process.env.UNI_INPUT_DIR);
}
catch (err) {
if (err.loc) {
const error = (0, uni_cli_shared_1.createRollupError)('uni:app-pages', 'pages.json', err, code);
this.error(error);
}
else {
throw err;
}
}
}
return {
code: registerGlobalCode(resolvedConfig, ssr) +
generatePagesJsonCode(ssr, code, resolvedConfig),
map: { mappings: '' },
};
}
},
};
});
}
exports.uniPagesJsonPlugin = uniPagesJsonPlugin;
function generatePagesJsonCode(ssr, jsonStr, config) {
const globalName = getGlobal(ssr);
const pagesJson = (0, uni_cli_shared_1.normalizePagesJson)(jsonStr, process.env.UNI_PLATFORM);
const { importLayoutComponentsCode, defineLayoutComponentsCode } = generateLayoutComponentsCode(globalName, pagesJson);
const definePagesCode = generatePagesDefineCode(pagesJson, config);
const uniRoutesCode = generateRoutes(globalName, pagesJson, config);
const uniConfigCode = generateConfig(globalName, pagesJson, config);
const cssCode = generateCssCode(config);
const vueType = process.env.UNI_APP_X === 'true' ? 'uvue' : 'nvue';
return `
import { defineAsyncComponent, resolveComponent, createVNode, withCtx, openBlock, createBlock } from 'vue'
import { PageComponent, useI18n, setupWindow, setupPage } from '@dcloudio/uni-h5'
import { appId, appName, appVersion, appVersionCode, debug, networkTimeout, router, async, sdkConfigs, qqMapKey, googleMapKey, aMapKey, bMapKey, aMapSecurityJsCode, aMapServiceHost, ${vueType}, locale, fallbackLocale, darkmode, themeConfig } from './${uni_cli_shared_1.MANIFEST_JSON_JS}'
const locales = import.meta.glob('./locale/*.json', { eager: true })
${importLayoutComponentsCode}
const extend = Object.assign
${cssCode}
${uniConfigCode}
${defineLayoutComponentsCode}
${definePagesCode}
${uniRoutesCode}
${config.command === 'serve' ? hmrCode : ''}
export {}
`;
}
const hmrCode = `if(import.meta.hot){
import.meta.hot.on('invalidate', (data) => {
import.meta.hot.invalidate()
})
}`;
function getGlobal(ssr) {
return ssr ? 'global' : 'window';
}
// 兼容 wx 对象
function registerGlobalCode(config, ssr) {
const name = getGlobal(ssr);
const enableTreeShaking = (0, uni_cli_shared_1.isEnableTreeShaking)((0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR));
if (enableTreeShaking && config.command === 'build' && !ssr) {
// 非 SSR 的发行模式,补充全局 uni 对象
return `import { upx2px, getApp } from '@dcloudio/uni-h5';${name}.uni = {};${name}.wx = {};${name}.rpx2px = upx2px`;
}
return `
import {uni,upx2px,getCurrentPages,getApp,UniServiceJSBridge,UniViewJSBridge} from '@dcloudio/uni-h5'
${name}.getApp = getApp
${name}.getCurrentPages = getCurrentPages
${name}.wx = uni
${name}.uni = uni
${name}.UniViewJSBridge = UniViewJSBridge
${name}.UniServiceJSBridge = UniServiceJSBridge
${name}.rpx2px = upx2px
${name}.__setupPage = (com)=>setupPage(com)
`;
}
function generateCssCode(config) {
const define = config.define;
const cssFiles = [uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'base.css'];
if (config.isProduction) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'shadow.css');
}
// if (define.__UNI_FEATURE_PAGES__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'async.css');
// }
if (define.__UNI_FEATURE_RESPONSIVE__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'layout.css');
}
if (define.__UNI_FEATURE_NAVIGATIONBAR__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'pageHead.css');
}
if (define.__UNI_FEATURE_TABBAR__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'tabBar.css');
}
// x 项目直接集成 uvue.css
if (process.env.UNI_APP_X === 'true') {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'uvue.css');
}
else {
if (define.__UNI_FEATURE_NVUE__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'nvue.css');
}
}
if (define.__UNI_FEATURE_PULL_DOWN_REFRESH__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'pageRefresh.css');
}
if (define.__UNI_FEATURE_NAVIGATIONBAR_SEARCHINPUT__) {
cssFiles.push(uni_cli_shared_1.BASE_COMPONENTS_STYLE_PATH + 'input.css');
}
const enableTreeShaking = (0, uni_cli_shared_1.isEnableTreeShaking)((0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR));
if (config.command === 'serve' || !enableTreeShaking) {
const apiDepsCss = (0, uni_cli_shared_1.API_DEPS_CSS)(process.env.UNI_APP_X === 'true');
// 开发模式或禁用摇树优化,自动添加所有API相关css
Object.keys(apiDepsCss).forEach((name) => {
const styles = apiDepsCss[name];
styles.forEach((style) => {
if (!cssFiles.includes(style)) {
cssFiles.push(style);
}
});
});
}
return cssFiles.map((file) => `import '${file}'`).join('\n');
}
function generateLayoutComponentsCode(globalName, pagesJson) {
const windowNames = {
topWindow: -1,
leftWindow: -2,
rightWindow: -3,
};
let importLayoutComponentsCode = '';
let defineLayoutComponentsCode = `${globalName}.__uniLayout = ${globalName}.__uniLayout || {}\n`;
Object.keys(windowNames).forEach((name) => {
const windowConfig = pagesJson[name];
if (windowConfig && windowConfig.path) {
importLayoutComponentsCode += `import ${name} from './${windowConfig.path}'\n`;
defineLayoutComponentsCode += `${globalName}.__uniConfig.${name}.component = setupWindow(${name},${windowNames[name]})\n`;
}
});
return {
importLayoutComponentsCode,
defineLayoutComponentsCode,
};
}
function generatePageDefineCode(pageOptions) {
let pagePathWithExtname = (0, uni_cli_shared_1.normalizePagePath)(pageOptions.path, 'h5');
if (!pagePathWithExtname) {
// 不存在时,仍引用,此时编译会报错文件不存在
pagePathWithExtname = pageOptions.path + '.vue';
}
const pageIdent = (0, uni_cli_shared_1.normalizeIdentifier)(pageOptions.path);
return `const ${pageIdent}Loader = ()=>import('./${pagePathWithExtname}').then(com => setupPage(com.default || com))
const ${pageIdent} = defineAsyncComponent(extend({loader:${pageIdent}Loader},AsyncComponentOptions))`;
}
function generatePagesDefineCode(pagesJson, _config) {
const { pages } = pagesJson;
return (`const AsyncComponentOptions = {
delay: async.delay,
timeout: async.timeout,
suspensible: async.suspensible
}
if(async.loading){
AsyncComponentOptions.loadingComponent = {
name:'SystemAsyncLoading',
render(){
return createVNode(resolveComponent(async.loading))
}
}
}
if(async.error){
AsyncComponentOptions.errorComponent = {
name:'SystemAsyncError',
render(){
return createVNode(resolveComponent(async.error))
}
}
}
` + pages.map((pageOptions) => generatePageDefineCode(pageOptions)).join('\n'));
}
function generatePageRoute({ path, meta }, _config) {
const { isEntry } = meta;
const alias = isEntry ? `\n alias:'/${path}',` : '';
// 目前单页面未处理 query=>props
return `{
path:'/${isEntry ? '' : path}',${alias}
component:{setup(){ const app = getApp(); const query = app && app.$route && app.$route.query || {}; return ()=>renderPage(${(0, uni_cli_shared_1.normalizeIdentifier)(path)},query)}},
loader: ${(0, uni_cli_shared_1.normalizeIdentifier)(path)}Loader,
meta: ${JSON.stringify(meta)}
}`;
}
function generatePagesRoute(pagesRouteOptions, config) {
return pagesRouteOptions.map((pageOptions) => generatePageRoute(pageOptions, config));
}
function generateRoutes(globalName, pagesJson, config) {
return `
function renderPage(component,props){
return (openBlock(), createBlock(PageComponent, null, {page: withCtx(() => [createVNode(component, extend({},props,{ref: "page"}), null, 512 /* NEED_PATCH */)]), _: 1 /* STABLE */}))
}
${globalName}.__uniRoutes=[${[
...generatePagesRoute((0, uni_cli_shared_1.normalizePagesRoute)(pagesJson), config),
].join(',')}].map(uniRoute=>(uniRoute.meta.route = (uniRoute.alias || uniRoute.path).slice(1),uniRoute))`;
}
function generateConfig(globalName, pagesJson, config) {
delete pagesJson.pages;
delete pagesJson.subPackages;
delete pagesJson.subpackages;
pagesJson.compilerVersion = process.env.UNI_COMPILER_VERSION;
const isX = process.env.UNI_APP_X === 'true';
const vueType = isX ? 'uvue' : 'nvue';
let tabBarCode = '';
if (isX) {
const tabBar = pagesJson.tabBar;
delete pagesJson.tabBar;
tabBarCode = `${globalName}.__uniConfig.getTabBarConfig = () => {return ${tabBar ? JSON.stringify(tabBar) : 'undefined'}};
${globalName}.__uniConfig.tabBar = __uniConfig.getTabBarConfig();`;
}
return `${isX ? `${globalName}.__uniX = true` : ''}
${globalName}.__uniConfig=extend(${JSON.stringify(pagesJson)},{
appId,
appName,
appVersion,
appVersionCode,
async,
debug,
networkTimeout,
sdkConfigs,
qqMapKey,
bMapKey,
googleMapKey,
aMapKey,
aMapSecurityJsCode,
aMapServiceHost,
${vueType},
locale,
fallbackLocale,
locales:Object.keys(locales).reduce((res,name)=>{const locale=name.replace(/\\.\\/locale\\/(uni-app.)?(.*).json/,'$2');extend(res[locale]||(res[locale]={}),locales[name].default);return res},{}),
router,
darkmode,
themeConfig,
})
${tabBarCode}
`;
}
+2
View File
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniPostVuePlugin(): Plugin;
+48
View File
@@ -0,0 +1,48 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniPostVuePlugin = void 0;
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const WXS_RE = /vue&type=(wxs|renderjs)/;
function uniPostVuePlugin() {
return {
name: 'uni:post-vue',
apply: 'serve',
enforce: 'post',
async transform(code, id) {
const { filename, query } = (0, uni_cli_shared_1.parseVueRequest)(id);
if (query.vue) {
return;
}
if (!uni_cli_shared_1.EXTNAME_VUE.includes(path_1.default.extname(filename))) {
return;
}
if (!WXS_RE.test(code)) {
return;
}
const hmrId = parseHmrId(code);
if (!hmrId) {
return;
}
// TODO 内部解决 @vitejs/plugin-vue 自定义块外链热刷的问题
// https://github.com/vitejs/vite/blob/main/packages/plugin-vue/src/main.ts#L387
// 没有增加 src=descriptor.id
// 包含外链 wxs,renderjs
code = code.replace(/vue&type=(wxs|renderjs)&index=([0-9]+)&src&/gi, (_, type, index) => {
return `vue&type=${type}&index=${index}&src=${hmrId}&`;
});
return {
code: code, // 暂不提供sourcemap,意义不大
map: null,
};
},
};
}
exports.uniPostVuePlugin = uniPostVuePlugin;
function parseHmrId(code) {
const matches = code.match(/_sfc_main.__hmrId = "(.*)"/);
return matches && matches[1];
}
+2
View File
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniRenderjsPlugin(): Plugin;
+47
View File
@@ -0,0 +1,47 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniRenderjsPlugin = void 0;
const debug_1 = __importDefault(require("debug"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const debugRenderjs = (0, debug_1.default)('uni:h5-renderjs');
function uniRenderjsPlugin() {
return {
name: 'uni:h5-renderjs',
transform(code, id) {
const { type, name } = (0, uni_cli_shared_1.parseRenderjs)(id);
if (!type) {
return;
}
debugRenderjs(id);
if (!name) {
this.error((0, uni_cli_shared_1.missingModuleName)(type, code));
}
return {
code: `${require('@vue/compiler-sfc').rewriteDefault(code.replace(/module\.exports\s*=/, 'export default '), '_sfc_' + type)}
${type === 'renderjs' ? genRenderjsCode(name) : genWxsCode(name)}`,
map: { mappings: '' },
};
},
};
}
exports.uniRenderjsPlugin = uniRenderjsPlugin;
function genRenderjsCode(name) {
return `export default Comp => {
if(!Comp.$renderjs){Comp.$renderjs = []}
Comp.$renderjs.push('${name}')
if(!Comp.mixins){Comp.mixins = []}
Comp.mixins.push({beforeCreate(){ this['${name}'] = this },mounted(){ this.$ownerInstance = this.$gcd(this, true) }})
Comp.mixins.push(_sfc_renderjs)
}`;
}
function genWxsCode(name) {
return `export default Comp => {
if(!Comp.$wxs){Comp.$wxs = []}
Comp.$wxs.push('${name}')
if(!Comp.mixins){Comp.mixins = []}
Comp.mixins.push({beforeCreate(){ this['${name}'] = _sfc_wxs }})
}`;
}
+2
View File
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniResolveIdPlugin(): Plugin;
+51
View File
@@ -0,0 +1,51 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniResolveIdPlugin = void 0;
const path_1 = __importDefault(require("path"));
const debug_1 = __importDefault(require("debug"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../utils");
const debugResolve = (0, debug_1.default)('uni:resolve');
function uniResolveIdPlugin() {
const resolveCache = {};
const mainPath = (0, uni_cli_shared_1.resolveMainPathOnce)(process.env.UNI_INPUT_DIR);
return {
name: 'uni:h5-resolve-id',
enforce: 'pre',
configResolved(config) {
resolveCache[utils_1.ownerModuleName] = (0, uni_cli_shared_1.resolveBuiltIn)(path_1.default.join(utils_1.ownerModuleName, (process.env.UNI_APP_X === 'true' ? 'dist-x' : 'dist') +
'/uni-h5.es.js'));
resolveCache['@dcloudio/uni-h5-vue'] = (0, uni_cli_shared_1.resolveBuiltIn)(path_1.default.join('@dcloudio/uni-h5-vue', (process.env.UNI_APP_X === 'true' ? 'dist-x' : 'dist') +
`/vue.runtime.${process.env.VITEST ? 'cjs' : 'esm'}.js`));
},
resolveId(id, importer, options) {
if (id === '/main' && importer && importer.endsWith('index.html')) {
return mainPath;
}
if (id === 'vue') {
id = '@dcloudio/uni-h5-vue';
}
if ((0, utils_1.isSSR)(options)) {
if (id === '@dcloudio/uni-h5-vue') {
return (0, uni_cli_shared_1.resolveBuiltIn)(path_1.default.join('@dcloudio/uni-h5-vue', (process.env.UNI_APP_X === 'true' ? 'dist-x' : 'dist') +
`/vue.runtime.cjs.js`));
}
}
const cache = resolveCache[id];
if (cache) {
debugResolve('cache', id, cache);
return cache;
}
if (id.startsWith('@dcloudio/uni-h5/style')) {
return (resolveCache[id] = (0, uni_cli_shared_1.resolveBuiltIn)(id));
}
if (id.startsWith('@dcloudio/uni-components/style')) {
return (resolveCache[id] = (0, uni_cli_shared_1.resolveBuiltIn)(id));
}
},
};
}
exports.uniResolveIdPlugin = uniResolveIdPlugin;
+2
View File
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniSetupPlugin(): Plugin;
+34
View File
@@ -0,0 +1,34 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniSetupPlugin = void 0;
const debug_1 = __importDefault(require("debug"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const debugSetup = (0, debug_1.default)('uni:setup');
function uniSetupPlugin() {
let appVuePath;
let resolvedConfig;
return {
name: 'uni:setup',
configResolved(config) {
resolvedConfig = config;
appVuePath = (0, uni_cli_shared_1.resolveAppVue)(process.env.UNI_INPUT_DIR);
},
transform(code, id) {
const { filename, query } = (0, uni_cli_shared_1.parseVueRequest)(id);
if (filename === appVuePath && !query.vue) {
debugSetup(filename);
return {
code: code +
`;import { setupApp } from '@dcloudio/uni-h5';setupApp(_sfc_main);`,
map: (0, uni_cli_shared_1.withSourcemap)(resolvedConfig)
? this.getCombinedSourcemap()
: null,
};
}
},
};
}
exports.uniSetupPlugin = uniSetupPlugin;
+2
View File
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniPostSourceMapPlugin(): Plugin;
+57
View File
@@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniPostSourceMapPlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const path_1 = require("path");
function uniPostSourceMapPlugin() {
return {
name: 'uni:post-sourcemap',
apply: 'serve',
enforce: 'post',
configureServer(server) {
// cli 工程呢?
// 重要:hack 了 _pendingRequests,来修改 map
const pendingRequests = new PendingRequests();
pendingRequests._server = server;
pendingRequests._inputDir = (0, uni_cli_shared_1.normalizePath)(process.env.UNI_INPUT_DIR);
// @ts-expect-error
server._pendingRequests = pendingRequests;
},
};
}
exports.uniPostSourceMapPlugin = uniPostSourceMapPlugin;
function isSourceMap(map) {
return map && map.sources;
}
class PendingRequests extends Map {
set(key, value) {
const then = value.request.then;
// @ts-expect-error
value.request.then = (onFulfilled, onRejected) => {
// @ts-expect-error
return then.call(value.request, (request) => {
const map = request?.map;
if (map) {
// @ts-expect-error
const mod = this._server.moduleGraph._getUnresolvedUrlToModule(key);
if (mod && mod.file && (0, path_1.isAbsolute)(mod.file)) {
const dir = (0, uni_cli_shared_1.normalizePath)((0, path_1.dirname)(mod.file));
if (dir.startsWith(this._inputDir) && isSourceMap(map)) {
for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
const sourcePath = map.sources[sourcesIndex];
if (sourcePath) {
// 将相对路径转换为绝对路径
if (!(0, path_1.isAbsolute)(sourcePath)) {
map.sources[sourcesIndex] = (0, uni_cli_shared_1.normalizePath)((0, path_1.join)(dir, sourcePath));
}
}
}
}
}
}
return onFulfilled?.(request);
}, onRejected);
};
return super.set(key, value);
}
}
+2
View File
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniSSRPlugin(): Plugin;
+67
View File
@@ -0,0 +1,67 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniSSRPlugin = void 0;
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../utils");
const ENTRY_SERVER_JS = 'entry-server.js';
function uniSSRPlugin() {
let entryServerJs;
let resolvedConfig;
const entryServerJsCode = (0, utils_1.generateSsrEntryServerCode)();
return {
name: 'uni:h5-ssr',
config(userConfig, env) {
if ((0, uni_cli_shared_1.isSsr)(env.command, userConfig)) {
(0, utils_1.initSsrAliasOnce)();
(0, utils_1.rewriteSsrVue)();
(0, utils_1.rewriteSsrNativeTag)();
(0, utils_1.rewriteSsrRenderStyle)(process.env.UNI_INPUT_DIR);
return {
resolve: {
alias: [
{
find: 'vue/server-renderer',
replacement: path_1.default.dirname((0, uni_cli_shared_1.resolveBuiltIn)('@vue/server-renderer')),
},
{
find: 'vuex',
replacement: path_1.default.dirname((0, uni_cli_shared_1.resolveBuiltIn)('vuex/package.json')),
},
],
},
};
}
},
configResolved(config) {
resolvedConfig = config;
entryServerJs = path_1.default.join(process.env.UNI_INPUT_DIR, ENTRY_SERVER_JS);
if ((0, uni_cli_shared_1.isSsr)(resolvedConfig.command, resolvedConfig)) {
(0, utils_1.initSsrDefine)(resolvedConfig);
}
},
resolveId(id) {
if (id.endsWith(ENTRY_SERVER_JS)) {
return entryServerJs;
}
},
load(id) {
if (id.endsWith(ENTRY_SERVER_JS)) {
return entryServerJsCode;
}
},
generateBundle(_options, bundle) {
const chunk = bundle['entry-server.js'];
if (chunk) {
chunk.code =
(0, utils_1.generateSsrDefineCode)(resolvedConfig, (0, uni_cli_shared_1.parseRpx2UnitOnce)(process.env.UNI_INPUT_DIR, process.env.UNI_PLATFORM)) +
'\n' +
chunk.code;
}
},
};
}
exports.uniSSRPlugin = uniSSRPlugin;