UNPKG

weapp-vite

Version:

weapp-vite 一个现代化的小程序打包工具

593 lines (573 loc) 20.6 kB
import { UserConfig as UserConfig$1, InlineConfig, UserConfigFnObject, UserConfigExport } from 'vite'; import * as rolldown from 'rolldown'; import { InputOption, RolldownOutput, RolldownWatcher } from 'rolldown'; import { Options } from 'tsdown'; import { WrapPluginOptions } from 'vite-plugin-performance'; import { PluginOptions } from 'vite-tsconfig-paths'; import { R as Resolver, a as ResolvedValue } from './types-D7SAXpSN.cjs'; import { Theme, Sitemap, App, Page, Component, Plugin } from '@weapp-core/schematics'; import { DetectResult } from 'package-manager-detector'; import { PackageJson } from 'pkg-types'; import { LRUCache } from 'lru-cache'; import * as node_modules_rolldown_dist_shared_binding_BO7hG1pA_mjs from 'node_modules/rolldown/dist/shared/binding-BO7hG1pA.mjs'; import * as node_modules_rolldown_dist_shared_define_config_CgND8XFH_mjs from 'node_modules/rolldown/dist/shared/define-config-CgND8XFH.mjs'; import PQueue from 'p-queue'; import { Buffer } from 'node:buffer'; interface Alias { find: string | RegExp; replacement: string; } interface ResolvedAlias { find: string | RegExp; replacement: string; } interface AliasOptions { /** * @example * ```js entries: [ { find: '@', replacement: path.resolve(import.meta.dirname, 'components'), }, ], * ``` 这样你就可以在 json 里面使用: ```json { "usingComponents": { "navigation-bar": "@/navigation-bar/navigation-bar", "ice-avatar": "@/avatar/avatar" } } ``` * 详见[json别名](/guide/alias.html#json-别名)文档 */ entries?: readonly Alias[] | { [find: string]: string; }; } type MpPlatform = 'weapp' | 'alipay' | 'tt'; interface SubPackage { pages: string[]; root: string; independent?: boolean; entry?: string; name?: string; dependencies?: (string | RegExp)[]; } type GenerateExtensionsOptions = Partial<{ js: 'js' | 'ts' | (string & {}); json: 'js' | 'ts' | 'json' | (string & {}); wxml: 'wxml' | (string & {}); wxss: 'wxss' | 'scss' | 'less' | 'css' | (string & {}); }>; type GenerateDirsOptions = Partial<{ app: string; page: string; component: string; }>; type GenerateFilenamesOptions = Partial<{ app: string; page: string; component: string; }>; interface GenerateOptions { /** * 生成文件的扩展名 */ extensions?: GenerateExtensionsOptions; /** * 默认生成文件的相对路径 */ dirs?: GenerateDirsOptions; /** * 默认生成文件的名称 */ filenames?: GenerateFilenamesOptions; } interface CopyOptions { include?: CopyGlobs; exclude?: CopyGlobs; filter?: (filePath: string, index: number, array: string[]) => boolean; } type CopyGlobs = string[]; interface AutoImportComponents { /** * 自动导入组件 */ globs?: string[]; /** * 自动导入组件解析器 */ resolvers?: Resolver[]; } type EnhanceWxmlOptions = ScanWxmlOptions & HandleWxmlOptions; interface ScanWxmlOptions { excludeComponent?: (tagName: string) => boolean; platform?: MpPlatform; } interface HandleWxmlOptions { removeComment?: boolean; transformEvent?: boolean; } interface EnhanceOptions { /** * wxml 增强 */ wxml?: boolean | (Partial<Omit<EnhanceWxmlOptions, 'platform'>>); /** * wxs 增强 */ wxs?: boolean; /** * 自动导入小程序组件 */ autoImportComponents?: AutoImportComponents; } interface BuildNpmPackageMeta { name: string; entry: InputOption; } interface WeappViteConfig { /** * @description 应用入口目录 (app.json 所在的目录) * 默认 js 模板在根目录 `.`,ts 模板在 `miniprogram` 目录,当然你可以把所有代码放在 `src` 目录下,并设置此选项为 `src` * @default '.' */ srcRoot?: string; /** * @description 插件入口目录 (plugin.json 所在的目录) * @default undefined */ pluginRoot?: string; /** * @group json 配置 * 文件引入别名 */ jsonAlias?: AliasOptions; /** * * @group 构建 npm */ npm?: { /** * @description 是否开启构建 npm 功能, 默认为 true * @default true */ enable?: boolean; /** * @description 是否开启缓存,默认为 true * @default true */ cache?: boolean; /** * @description 构建 npm 的配置,可以配置这个选项给 tsdown,让不同的包走不同的配置 */ buildOptions?: (options: Options, pkgMeta: BuildNpmPackageMeta) => Options | undefined; }; /** * @group 生成脚手架配置 * weapp-vite generate 相关的配置 */ generate?: GenerateOptions; /** * @group 插件集成 * 传递给内置 [`vite-tsconfig-paths`](https://www.npmjs.com/package/vite-tsconfig-paths) 插件的参数 */ tsconfigPaths?: PluginOptions; /** * @group 分包配置 * 分包是否独立的 rollup 编译上下文 * 默认情况下,当一个分包设置了 independent: true 之后会默认启用 * 可以设置 key: 为 root, value: {independent:true} 来强制启用 独立的 rollup 编译上下文 */ subPackages?: Record<string, Pick<SubPackage, 'independent' | 'dependencies'> & { autoImportComponents?: AutoImportComponents; }>; /** * 需要被额外包括的资源 * 默认情况下包括大部分的图片资源格式 */ copy?: CopyOptions; /** * @description 额外的 wxml 文件 * 把这个方法,扫描到的 `wxml` 添加到额外的 `wxml` 文件列表, **处理** 之后输出到最终的产物中 * @param wxmlFilePath * @returns boolean */ isAdditionalWxml?: (wxmlFilePath: string) => boolean; /** * @description 编译目标平台 * @ignore */ platform?: MpPlatform; /** * 增强配置 */ enhance?: EnhanceOptions; debug?: { watchFiles?: (watchFiles: string[], subPackageMeta?: SubPackageMetaValue) => void; resolveId?: (id: string, subPackageMeta?: SubPackageMetaValue) => void; load?: (id: string, subPackageMeta?: SubPackageMetaValue) => void; inspect?: WrapPluginOptions; }; /** * @description 构建 worker 配置 */ worker?: { /** * @description 构建 worker 的入口 */ entry?: string | string[]; }; } type UserConfig = UserConfig$1 & { weapp?: WeappViteConfig; }; interface ProjectConfig { miniprogramRoot?: string; srcMiniprogramRoot?: string; setting?: { packNpmManually?: boolean; packNpmRelationList?: { packageJsonPath: string; miniprogramNpmDistDir: string; }[]; }; } interface SubPackageMetaValue { entries: string[]; subPackage: SubPackage; } interface WxmlDep { tagName: string; start: number; end: number; quote: string | null | undefined; name: string; value: string; attrs: Record<string, string>; } interface ScanComponentItem { start: number; end: number; } type ComponentsMap = Record<string, ScanComponentItem[]>; interface BaseEntry { path: string; jsonPath?: string; json?: object; type: 'app' | 'page' | 'component' | (string & {}); } type Entry = AppEntry | PageEntry | ComponentEntry; /** * 应用入口 js + json */ interface AppEntry extends BaseEntry { type: 'app'; themeJsonPath?: string; themeJson?: Theme; sitemapJsonPath?: string; sitemapJson?: Sitemap; json: App; jsonPath: string; } /** * 页面入口 js + wxml */ interface PageEntry extends BaseEntry { type: 'page'; templatePath: string; json?: Page; } /** * 组件入口 js + wxml + json + json.component === true */ interface ComponentEntry extends BaseEntry { type: 'component'; templatePath: string; json: Component; jsonPath: string; } type EntryJsonFragment = Omit<BaseEntry, 'path' | 'type'>; declare class AutoImportService { private readonly configService; private readonly jsonService; potentialComponentMap: Map<string, { entry: Entry; value: ResolvedValue; }>; constructor(configService: ConfigService, jsonService: JsonService); scanPotentialComponentEntries(filePath: string): Promise<void>; filter(id: string, _meta?: SubPackageMetaValue): boolean; } interface BuildOptions { skipNpm?: boolean; } declare class BuildService { readonly configService: ConfigService; readonly watcherService: WatcherService; readonly npmService: NpmService; readonly scanService: ScanService; queue: PQueue; constructor(configService: ConfigService, watcherService: WatcherService, npmService: NpmService, scanService: ScanService); checkWorkersOptions(): this is this & { scanService: { workersDir: string; }; }; devWorkers(): Promise<void>; buildWorkers(): Promise<void>; private runDev; private runProd; build(options?: BuildOptions): Promise<{ listeners: Map<"close" | "change" | "event" | "restart", Array<(...parameters: any[]) => node_modules_rolldown_dist_shared_define_config_CgND8XFH_mjs.MaybePromise<void>>>; timer: any; on(event: "change", listener: (id: string, change: { event: "delete" | "update" | "create"; }) => node_modules_rolldown_dist_shared_define_config_CgND8XFH_mjs.MaybePromise<void>): /*elided*/ any; on(event: "event", listener: (data: rolldown.RolldownWatcherEvent) => node_modules_rolldown_dist_shared_define_config_CgND8XFH_mjs.MaybePromise<void>): /*elided*/ any; on(event: "restart" | "close", listener: () => node_modules_rolldown_dist_shared_define_config_CgND8XFH_mjs.MaybePromise<void>): /*elided*/ any; off(event: "close" | "change" | "event" | "restart", listener: (...parameters: any[]) => node_modules_rolldown_dist_shared_define_config_CgND8XFH_mjs.MaybePromise<void>): /*elided*/ any; clear(event: "close" | "change" | "event" | "restart"): void; onEvent(event: node_modules_rolldown_dist_shared_binding_BO7hG1pA_mjs.BindingWatcherEvent): Promise<void>; close(): Promise<void>; } | RolldownOutput | RolldownOutput[]>; } interface OutputExtensions { js: string; json: string; wxml: string; wxss: string; wxs?: string; } interface LoadConfigOptions { cwd: string; isDev: boolean; mode: string; inlineConfig?: InlineConfig; } interface LoadConfigResult { config: InlineConfig; aliasEntries: ResolvedAlias[]; outputExtensions: OutputExtensions; packageJson: PackageJson; relativeSrcRoot: (p: string) => string; cwd: string; isDev: boolean; mode: string; projectConfig: Record<string, any>; mpDistRoot: string; packageJsonPath: string; platform: MpPlatform; srcRoot: string; } interface PackageInfo { name: string; version: string | undefined; rootPath: string; packageJsonPath: string; packageJson: PackageJson; } declare class ConfigService { options: LoadConfigResult; outputExtensions: OutputExtensions; /** * esbuild 定义的环境变量 */ defineEnv: Record<string, any>; packageManager: DetectResult; packageInfo: PackageInfo; constructor(); get defineImportMetaEnv(): Record<string, any>; setDefineEnv(key: string, value: any): void; loadConfig(opts: LoadConfigOptions): Promise<{ config: InlineConfig; aliasEntries: ResolvedAlias[]; outputExtensions: OutputExtensions; packageJson: PackageJson; relativeSrcRoot: (p: string) => string; cwd: string; isDev: boolean; mode: string; projectConfig: ProjectConfig; mpDistRoot: string; packageJsonPath: string; platform: MpPlatform; srcRoot: string; } | undefined>; load(options?: Partial<LoadConfigOptions>): Promise<Required<LoadConfigResult>>; get cwd(): string; get isDev(): boolean; get mpDistRoot(): string; get outDir(): string; get inlineConfig(): InlineConfig; get weappViteConfig(): WeappViteConfig | undefined; get packageJson(): PackageJson; get projectConfig(): Record<string, any>; get srcRoot(): string; get pluginRoot(): string | undefined; get absolutePluginRoot(): string | undefined; get absoluteSrcRoot(): string; get mode(): string; get aliasEntries(): ResolvedAlias[]; get platform(): MpPlatform; relativeCwd(p: string): string; relativeSrcRoot(p: string): string; relativeAbsoluteSrcRoot(p: string): string; mergeWorkers(...configs: Partial<InlineConfig>[]): InlineConfig; merge(subPackageMeta?: SubPackageMetaValue, ...configs: Partial<InlineConfig>[]): InlineConfig; } declare class FileCache<T extends object> { cache: LRUCache<string, T>; mtimeMap: Map<string, number>; constructor(max?: number); get(id: string): T | undefined; set(id: string, content: T): LRUCache<string, T, unknown>; delete(id: string): boolean; isInvalidate(id: string): Promise<boolean>; } declare class JsonService { private readonly configService; cache: FileCache<any>; constructor(configService: ConfigService); read(filepath: string): Promise<any>; resolve(entry: Partial<Pick<Entry, 'json' | 'jsonPath' | 'type'>>): string | undefined; } declare class NpmService { private readonly configService; private readonly scanService; constructor(configService: ConfigService, scanService: ScanService); getDependenciesCacheFilePath(key?: string): string; get dependenciesCacheHash(): string; isMiniprogramPackage(pkg: PackageJson): boolean; shouldSkipBuild(outDir: string, isOutdated: boolean): Promise<boolean>; writeDependenciesCache(root?: string): Promise<void> | undefined; readDependenciesCache(root?: string): Promise<any>; checkDependenciesCacheOutdate(root?: string): Promise<boolean>; bundleBuild({ entry, name, options, outDir }: { entry: InputOption; name: string; options?: Options; outDir: string; }): Promise<void>; copyBuild({ from, to }: { from: string; to: string; name: string; }): Promise<void>; buildPackage({ dep, outDir, options, isDependenciesCacheOutdate }: { dep: string; outDir: string; options?: Options; isDependenciesCacheOutdate: boolean; }): Promise<void>; getPackNpmRelationList(): { packageJsonPath: string; miniprogramNpmDistDir: string; }[]; build(options?: Options): Promise<void>; } declare class ScanService { private readonly configService; private readonly jsonService; appEntry?: AppEntry; subPackageMap: Map<string, SubPackageMetaValue>; pluginJson?: Plugin; constructor(configService: ConfigService, jsonService: JsonService); loadAppEntry(): Promise<AppEntry>; loadIndependentSubPackage(): SubPackageMetaValue[]; isMainPackageFileName(fileName: string): boolean; get workersOptions(): string | { [k: string]: unknown; path?: string; isSubpackage?: boolean; } | undefined; get workersDir(): string | undefined; } declare class WatcherService { rollupWatcherMap: Map<string, RolldownWatcher>; constructor(); getRollupWatcher(root?: string): { listeners: Map<"close" | "change" | "event" | "restart", Array<(...parameters: any[]) => node_modules_rolldown_dist_shared_define_config_CgND8XFH_mjs.MaybePromise<void>>>; timer: any; on(event: "change", listener: (id: string, change: { event: "delete" | "update" | "create"; }) => node_modules_rolldown_dist_shared_define_config_CgND8XFH_mjs.MaybePromise<void>): /*elided*/ any; on(event: "event", listener: (data: rolldown.RolldownWatcherEvent) => node_modules_rolldown_dist_shared_define_config_CgND8XFH_mjs.MaybePromise<void>): /*elided*/ any; on(event: "restart" | "close", listener: () => node_modules_rolldown_dist_shared_define_config_CgND8XFH_mjs.MaybePromise<void>): /*elided*/ any; off(event: "close" | "change" | "event" | "restart", listener: (...parameters: any[]) => node_modules_rolldown_dist_shared_define_config_CgND8XFH_mjs.MaybePromise<void>): /*elided*/ any; clear(event: "close" | "change" | "event" | "restart"): void; onEvent(event: node_modules_rolldown_dist_shared_binding_BO7hG1pA_mjs.BindingWatcherEvent): Promise<void>; close(): Promise<void>; } | undefined; setRollupWatcher(watcher: RolldownWatcher, root?: string): void; closeAll(): void; close(root?: string): void; } interface Token { start: number; end: number; value: string; } interface WxmlToken { components: ComponentsMap; deps: WxmlDep[]; removeStartStack: number[]; removeEndStack: number[]; commentTokens: Token[]; inlineWxsTokens: Token[]; wxsImportNormalizeTokens: Token[]; removeWxsLangAttrTokens: Token[]; eventTokens: Token[]; code: string; } declare function scanWxml(wxml: string | Buffer, options?: ScanWxmlOptions): WxmlToken; type ScanWxmlResult = ReturnType<typeof scanWxml>; declare class WxmlService { private readonly configService; depsMap: Map<string, Set<string>>; tokenMap: Map<string, ScanWxmlResult>; wxmlComponentsMap: Map<string, ComponentsMap>; constructor(configService: ConfigService); addDeps(filepath: string, deps?: string[]): Promise<void>; getAllDeps(): Set<string>; clearAll(): void; analyze(wxml: string): WxmlToken; scan(filepath: string): Promise<WxmlToken | undefined>; setWxmlComponentsMap(absPath: string, components: ComponentsMap): void; } declare class CompilerContext { readonly configService: ConfigService; readonly npmService: NpmService; readonly wxmlService: WxmlService; readonly jsonService: JsonService; readonly watcherService: WatcherService; readonly autoImportService: AutoImportService; readonly buildService: BuildService; readonly scanService: ScanService; /** * 构造函数用于初始化编译器上下文对象 * @param options 可选的编译器上下文配置对象 */ constructor(configService: ConfigService, npmService: NpmService, wxmlService: WxmlService, jsonService: JsonService, watcherService: WatcherService, autoImportService: AutoImportService, buildService: BuildService, scanService: ScanService); } type ReturnSelf<T> = (config: T) => T; type ConfigFn<T> = T | ((ctx: CompilerContext) => T); type DefineJsonFn<T> = ReturnSelf<ConfigFn<T>>; declare const defineAppJson: DefineJsonFn<App>; declare const definePageJson: DefineJsonFn<Page>; declare const defineComponentJson: DefineJsonFn<Component>; declare const defineSitemapJson: DefineJsonFn<Sitemap>; declare const defineThemeJson: DefineJsonFn<Theme>; declare module 'vite' { interface UserConfig { weapp?: WeappViteConfig; } } declare function defineConfig(config: UserConfig$1): UserConfig$1; declare function defineConfig(config: Promise<UserConfig$1>): Promise<UserConfig$1>; declare function defineConfig(config: UserConfigFnObject): UserConfigFnObject; declare function defineConfig(config: UserConfigExport): UserConfigExport; export { type Alias as A, type BuildNpmPackageMeta as B, CompilerContext as C, type EnhanceWxmlOptions as E, type GenerateExtensionsOptions as G, type HandleWxmlOptions as H, type LoadConfigOptions as L, type MpPlatform as M, type ProjectConfig as P, type ResolvedAlias as R, type SubPackage as S, type UserConfig as U, type WeappViteConfig as W, defineAppJson as a, definePageJson as b, defineComponentJson as c, defineConfig as d, defineSitemapJson as e, defineThemeJson as f, type AliasOptions as g, type GenerateDirsOptions as h, type GenerateFilenamesOptions as i, type GenerateOptions as j, type CopyOptions as k, type CopyGlobs as l, type AutoImportComponents as m, type ScanWxmlOptions as n, type EnhanceOptions as o, type SubPackageMetaValue as p, type WxmlDep as q, type ScanComponentItem as r, type ComponentsMap as s, type BaseEntry as t, type Entry as u, type AppEntry as v, type PageEntry as w, type ComponentEntry as x, type EntryJsonFragment as y };