compiler-sfc.d.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. import * as _babel_types from '@babel/types';
  2. import { Statement, Expression, TSType, Node, Program, CallExpression, ObjectPattern, TSModuleDeclaration, TSPropertySignature, TSMethodSignature, TSCallSignatureDeclaration, TSFunctionType } from '@babel/types';
  3. import { RootNode, CompilerOptions, CodegenResult, ParserOptions, CompilerError, RawSourceMap, SourceLocation, BindingMetadata as BindingMetadata$1 } from '@vue/compiler-core';
  4. export { BindingMetadata, CompilerError, CompilerOptions, extractIdentifiers, generateCodeFrame, isInDestructureAssignment, isStaticProperty, walkIdentifiers } from '@vue/compiler-core';
  5. import { ParserPlugin } from '@babel/parser';
  6. export { parse as babelParse } from '@babel/parser';
  7. import { Result, LazyResult } from 'postcss';
  8. import MagicString from 'magic-string';
  9. export { default as MagicString } from 'magic-string';
  10. import TS from 'typescript';
  11. export interface AssetURLTagConfig {
  12. [name: string]: string[];
  13. }
  14. export interface AssetURLOptions {
  15. /**
  16. * If base is provided, instead of transforming relative asset urls into
  17. * imports, they will be directly rewritten to absolute urls.
  18. */
  19. base?: string | null;
  20. /**
  21. * If true, also processes absolute urls.
  22. */
  23. includeAbsolute?: boolean;
  24. tags?: AssetURLTagConfig;
  25. }
  26. export interface TemplateCompiler {
  27. compile(source: string | RootNode, options: CompilerOptions): CodegenResult;
  28. parse(template: string, options: ParserOptions): RootNode;
  29. }
  30. export interface SFCTemplateCompileResults {
  31. code: string;
  32. ast?: RootNode;
  33. preamble?: string;
  34. source: string;
  35. tips: string[];
  36. errors: (string | CompilerError)[];
  37. map?: RawSourceMap;
  38. }
  39. export interface SFCTemplateCompileOptions {
  40. source: string;
  41. ast?: RootNode;
  42. filename: string;
  43. id: string;
  44. scoped?: boolean;
  45. slotted?: boolean;
  46. isProd?: boolean;
  47. ssr?: boolean;
  48. ssrCssVars?: string[];
  49. inMap?: RawSourceMap;
  50. compiler?: TemplateCompiler;
  51. compilerOptions?: CompilerOptions;
  52. preprocessLang?: string;
  53. preprocessOptions?: any;
  54. /**
  55. * In some cases, compiler-sfc may not be inside the project root (e.g. when
  56. * linked or globally installed). In such cases a custom `require` can be
  57. * passed to correctly resolve the preprocessors.
  58. */
  59. preprocessCustomRequire?: (id: string) => any;
  60. /**
  61. * Configure what tags/attributes to transform into asset url imports,
  62. * or disable the transform altogether with `false`.
  63. */
  64. transformAssetUrls?: AssetURLOptions | AssetURLTagConfig | boolean;
  65. }
  66. export declare function compileTemplate(options: SFCTemplateCompileOptions): SFCTemplateCompileResults;
  67. export interface SFCScriptCompileOptions {
  68. /**
  69. * Scope ID for prefixing injected CSS variables.
  70. * This must be consistent with the `id` passed to `compileStyle`.
  71. */
  72. id: string;
  73. /**
  74. * Production mode. Used to determine whether to generate hashed CSS variables
  75. */
  76. isProd?: boolean;
  77. /**
  78. * Enable/disable source map. Defaults to true.
  79. */
  80. sourceMap?: boolean;
  81. /**
  82. * https://babeljs.io/docs/en/babel-parser#plugins
  83. */
  84. babelParserPlugins?: ParserPlugin[];
  85. /**
  86. * A list of files to parse for global types to be made available for type
  87. * resolving in SFC macros. The list must be fully resolved file system paths.
  88. */
  89. globalTypeFiles?: string[];
  90. /**
  91. * Compile the template and inline the resulting render function
  92. * directly inside setup().
  93. * - Only affects `<script setup>`
  94. * - This should only be used in production because it prevents the template
  95. * from being hot-reloaded separately from component state.
  96. */
  97. inlineTemplate?: boolean;
  98. /**
  99. * Generate the final component as a variable instead of default export.
  100. * This is useful in e.g. @vitejs/plugin-vue where the script needs to be
  101. * placed inside the main module.
  102. */
  103. genDefaultAs?: string;
  104. /**
  105. * Options for template compilation when inlining. Note these are options that
  106. * would normally be passed to `compiler-sfc`'s own `compileTemplate()`, not
  107. * options passed to `compiler-dom`.
  108. */
  109. templateOptions?: Partial<SFCTemplateCompileOptions>;
  110. /**
  111. * Hoist <script setup> static constants.
  112. * - Only enables when one `<script setup>` exists.
  113. * @default true
  114. */
  115. hoistStatic?: boolean;
  116. /**
  117. * Set to `false` to disable reactive destructure for `defineProps` (pre-3.5
  118. * behavior), or set to `'error'` to throw hard error on props destructures.
  119. * @default true
  120. */
  121. propsDestructure?: boolean | 'error';
  122. /**
  123. * File system access methods to be used when resolving types
  124. * imported in SFC macros. Defaults to ts.sys in Node.js, can be overwritten
  125. * to use a virtual file system for use in browsers (e.g. in REPLs)
  126. */
  127. fs?: {
  128. fileExists(file: string): boolean;
  129. readFile(file: string): string | undefined;
  130. realpath?(file: string): string;
  131. };
  132. /**
  133. * Transform Vue SFCs into custom elements.
  134. */
  135. customElement?: boolean | ((filename: string) => boolean);
  136. }
  137. interface ImportBinding {
  138. isType: boolean;
  139. imported: string;
  140. local: string;
  141. source: string;
  142. isFromSetup: boolean;
  143. isUsedInTemplate: boolean;
  144. }
  145. /**
  146. * Compile `<script setup>`
  147. * It requires the whole SFC descriptor because we need to handle and merge
  148. * normal `<script>` + `<script setup>` if both are present.
  149. */
  150. export declare function compileScript(sfc: SFCDescriptor, options: SFCScriptCompileOptions): SFCScriptBlock;
  151. export interface SFCParseOptions {
  152. filename?: string;
  153. sourceMap?: boolean;
  154. sourceRoot?: string;
  155. pad?: boolean | 'line' | 'space';
  156. ignoreEmpty?: boolean;
  157. compiler?: TemplateCompiler;
  158. templateParseOptions?: ParserOptions;
  159. }
  160. export interface SFCBlock {
  161. type: string;
  162. content: string;
  163. attrs: Record<string, string | true>;
  164. loc: SourceLocation;
  165. map?: RawSourceMap;
  166. lang?: string;
  167. src?: string;
  168. }
  169. export interface SFCTemplateBlock extends SFCBlock {
  170. type: 'template';
  171. ast?: RootNode;
  172. }
  173. export interface SFCScriptBlock extends SFCBlock {
  174. type: 'script';
  175. setup?: string | boolean;
  176. bindings?: BindingMetadata$1;
  177. imports?: Record<string, ImportBinding>;
  178. scriptAst?: _babel_types.Statement[];
  179. scriptSetupAst?: _babel_types.Statement[];
  180. warnings?: string[];
  181. /**
  182. * Fully resolved dependency file paths (unix slashes) with imported types
  183. * used in macros, used for HMR cache busting in @vitejs/plugin-vue and
  184. * vue-loader.
  185. */
  186. deps?: string[];
  187. }
  188. export interface SFCStyleBlock extends SFCBlock {
  189. type: 'style';
  190. scoped?: boolean;
  191. module?: string | boolean;
  192. }
  193. export interface SFCDescriptor {
  194. filename: string;
  195. source: string;
  196. template: SFCTemplateBlock | null;
  197. script: SFCScriptBlock | null;
  198. scriptSetup: SFCScriptBlock | null;
  199. styles: SFCStyleBlock[];
  200. customBlocks: SFCBlock[];
  201. cssVars: string[];
  202. /**
  203. * whether the SFC uses :slotted() modifier.
  204. * this is used as a compiler optimization hint.
  205. */
  206. slotted: boolean;
  207. /**
  208. * compare with an existing descriptor to determine whether HMR should perform
  209. * a reload vs. re-render.
  210. *
  211. * Note: this comparison assumes the prev/next script are already identical,
  212. * and only checks the special case where <script setup lang="ts"> unused import
  213. * pruning result changes due to template changes.
  214. */
  215. shouldForceReload: (prevImports: Record<string, ImportBinding>) => boolean;
  216. }
  217. export interface SFCParseResult {
  218. descriptor: SFCDescriptor;
  219. errors: (CompilerError | SyntaxError)[];
  220. }
  221. export declare function parse(source: string, options?: SFCParseOptions): SFCParseResult;
  222. type PreprocessLang = 'less' | 'sass' | 'scss' | 'styl' | 'stylus';
  223. export interface SFCStyleCompileOptions {
  224. source: string;
  225. filename: string;
  226. id: string;
  227. scoped?: boolean;
  228. trim?: boolean;
  229. isProd?: boolean;
  230. inMap?: RawSourceMap;
  231. preprocessLang?: PreprocessLang;
  232. preprocessOptions?: any;
  233. preprocessCustomRequire?: (id: string) => any;
  234. postcssOptions?: any;
  235. postcssPlugins?: any[];
  236. /**
  237. * @deprecated use `inMap` instead.
  238. */
  239. map?: RawSourceMap;
  240. }
  241. /**
  242. * Aligns with postcss-modules
  243. * https://github.com/css-modules/postcss-modules
  244. */
  245. interface CSSModulesOptions {
  246. scopeBehaviour?: 'global' | 'local';
  247. generateScopedName?: string | ((name: string, filename: string, css: string) => string);
  248. hashPrefix?: string;
  249. localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly';
  250. exportGlobals?: boolean;
  251. globalModulePaths?: RegExp[];
  252. }
  253. export interface SFCAsyncStyleCompileOptions extends SFCStyleCompileOptions {
  254. isAsync?: boolean;
  255. modules?: boolean;
  256. modulesOptions?: CSSModulesOptions;
  257. }
  258. export interface SFCStyleCompileResults {
  259. code: string;
  260. map: RawSourceMap | undefined;
  261. rawResult: Result | LazyResult | undefined;
  262. errors: Error[];
  263. modules?: Record<string, string>;
  264. dependencies: Set<string>;
  265. }
  266. export declare function compileStyle(options: SFCStyleCompileOptions): SFCStyleCompileResults;
  267. export declare function compileStyleAsync(options: SFCAsyncStyleCompileOptions): Promise<SFCStyleCompileResults>;
  268. export declare function rewriteDefault(input: string, as: string, parserPlugins?: ParserPlugin[]): string;
  269. /**
  270. * Utility for rewriting `export default` in a script block into a variable
  271. * declaration so that we can inject things into it
  272. */
  273. export declare function rewriteDefaultAST(ast: Statement[], s: MagicString, as: string): void;
  274. type PropsDestructureBindings = Record<string, // public prop key
  275. {
  276. local: string;
  277. default?: Expression;
  278. }>;
  279. export declare function extractRuntimeProps(ctx: TypeResolveContext): string | undefined;
  280. interface ModelDecl {
  281. type: TSType | undefined;
  282. options: string | undefined;
  283. identifier: string | undefined;
  284. runtimeOptionNodes: Node[];
  285. }
  286. declare enum BindingTypes {
  287. /**
  288. * returned from data()
  289. */
  290. DATA = "data",
  291. /**
  292. * declared as a prop
  293. */
  294. PROPS = "props",
  295. /**
  296. * a local alias of a `<script setup>` destructured prop.
  297. * the original is stored in __propsAliases of the bindingMetadata object.
  298. */
  299. PROPS_ALIASED = "props-aliased",
  300. /**
  301. * a let binding (may or may not be a ref)
  302. */
  303. SETUP_LET = "setup-let",
  304. /**
  305. * a const binding that can never be a ref.
  306. * these bindings don't need `unref()` calls when processed in inlined
  307. * template expressions.
  308. */
  309. SETUP_CONST = "setup-const",
  310. /**
  311. * a const binding that does not need `unref()`, but may be mutated.
  312. */
  313. SETUP_REACTIVE_CONST = "setup-reactive-const",
  314. /**
  315. * a const binding that may be a ref.
  316. */
  317. SETUP_MAYBE_REF = "setup-maybe-ref",
  318. /**
  319. * bindings that are guaranteed to be refs
  320. */
  321. SETUP_REF = "setup-ref",
  322. /**
  323. * declared by other options, e.g. computed, inject
  324. */
  325. OPTIONS = "options",
  326. /**
  327. * a literal constant, e.g. 'foo', 1, true
  328. */
  329. LITERAL_CONST = "literal-const"
  330. }
  331. type BindingMetadata = {
  332. [key: string]: BindingTypes | undefined;
  333. } & {
  334. __isScriptSetup?: boolean;
  335. __propsAliases?: Record<string, string>;
  336. };
  337. export declare class ScriptCompileContext {
  338. descriptor: SFCDescriptor;
  339. options: Partial<SFCScriptCompileOptions>;
  340. isJS: boolean;
  341. isTS: boolean;
  342. isCE: boolean;
  343. scriptAst: Program | null;
  344. scriptSetupAst: Program | null;
  345. source: string;
  346. filename: string;
  347. s: MagicString;
  348. startOffset: number | undefined;
  349. endOffset: number | undefined;
  350. scope?: TypeScope;
  351. globalScopes?: TypeScope[];
  352. userImports: Record<string, ImportBinding>;
  353. hasDefinePropsCall: boolean;
  354. hasDefineEmitCall: boolean;
  355. hasDefineExposeCall: boolean;
  356. hasDefaultExportName: boolean;
  357. hasDefaultExportRender: boolean;
  358. hasDefineOptionsCall: boolean;
  359. hasDefineSlotsCall: boolean;
  360. hasDefineModelCall: boolean;
  361. propsCall: CallExpression | undefined;
  362. propsDecl: Node | undefined;
  363. propsRuntimeDecl: Node | undefined;
  364. propsTypeDecl: Node | undefined;
  365. propsDestructureDecl: ObjectPattern | undefined;
  366. propsDestructuredBindings: PropsDestructureBindings;
  367. propsDestructureRestId: string | undefined;
  368. propsRuntimeDefaults: Node | undefined;
  369. emitsRuntimeDecl: Node | undefined;
  370. emitsTypeDecl: Node | undefined;
  371. emitDecl: Node | undefined;
  372. modelDecls: Record<string, ModelDecl>;
  373. optionsRuntimeDecl: Node | undefined;
  374. bindingMetadata: BindingMetadata;
  375. helperImports: Set<string>;
  376. helper(key: string): string;
  377. /**
  378. * to be exposed on compiled script block for HMR cache busting
  379. */
  380. deps?: Set<string>;
  381. /**
  382. * cache for resolved fs
  383. */
  384. fs?: NonNullable<SFCScriptCompileOptions['fs']>;
  385. constructor(descriptor: SFCDescriptor, options: Partial<SFCScriptCompileOptions>);
  386. getString(node: Node, scriptSetup?: boolean): string;
  387. warn(msg: string, node: Node, scope?: TypeScope): void;
  388. error(msg: string, node: Node, scope?: TypeScope): never;
  389. }
  390. export type SimpleTypeResolveOptions = Partial<Pick<SFCScriptCompileOptions, 'globalTypeFiles' | 'fs' | 'babelParserPlugins' | 'isProd'>>;
  391. /**
  392. * TypeResolveContext is compatible with ScriptCompileContext
  393. * but also allows a simpler version of it with minimal required properties
  394. * when resolveType needs to be used in a non-SFC context, e.g. in a babel
  395. * plugin. The simplest context can be just:
  396. * ```ts
  397. * const ctx: SimpleTypeResolveContext = {
  398. * filename: '...',
  399. * source: '...',
  400. * options: {},
  401. * error() {},
  402. * ast: []
  403. * }
  404. * ```
  405. */
  406. export type SimpleTypeResolveContext = Pick<ScriptCompileContext, 'source' | 'filename' | 'error' | 'helper' | 'getString' | 'propsTypeDecl' | 'propsRuntimeDefaults' | 'propsDestructuredBindings' | 'emitsTypeDecl' | 'isCE'> & Partial<Pick<ScriptCompileContext, 'scope' | 'globalScopes' | 'deps' | 'fs'>> & {
  407. ast: Statement[];
  408. options: SimpleTypeResolveOptions;
  409. };
  410. export type TypeResolveContext = ScriptCompileContext | SimpleTypeResolveContext;
  411. type Import = Pick<ImportBinding, 'source' | 'imported'>;
  412. interface WithScope {
  413. _ownerScope: TypeScope;
  414. }
  415. type ScopeTypeNode = Node & WithScope & {
  416. _ns?: TSModuleDeclaration & WithScope;
  417. };
  418. declare class TypeScope {
  419. filename: string;
  420. source: string;
  421. offset: number;
  422. imports: Record<string, Import>;
  423. types: Record<string, ScopeTypeNode>;
  424. declares: Record<string, ScopeTypeNode>;
  425. constructor(filename: string, source: string, offset?: number, imports?: Record<string, Import>, types?: Record<string, ScopeTypeNode>, declares?: Record<string, ScopeTypeNode>);
  426. isGenericScope: boolean;
  427. resolvedImportSources: Record<string, string>;
  428. exportedTypes: Record<string, ScopeTypeNode>;
  429. exportedDeclares: Record<string, ScopeTypeNode>;
  430. }
  431. interface MaybeWithScope {
  432. _ownerScope?: TypeScope;
  433. }
  434. interface ResolvedElements {
  435. props: Record<string, (TSPropertySignature | TSMethodSignature) & {
  436. _ownerScope: TypeScope;
  437. }>;
  438. calls?: (TSCallSignatureDeclaration | TSFunctionType)[];
  439. }
  440. /**
  441. * Resolve arbitrary type node to a list of type elements that can be then
  442. * mapped to runtime props or emits.
  443. */
  444. export declare function resolveTypeElements(ctx: TypeResolveContext, node: Node & MaybeWithScope & {
  445. _resolvedElements?: ResolvedElements;
  446. }, scope?: TypeScope, typeParameters?: Record<string, Node>): ResolvedElements;
  447. /**
  448. * @private
  449. */
  450. export declare function registerTS(_loadTS: () => typeof TS): void;
  451. /**
  452. * @private
  453. */
  454. export declare function invalidateTypeCache(filename: string): void;
  455. export declare function inferRuntimeType(ctx: TypeResolveContext, node: Node & MaybeWithScope, scope?: TypeScope, isKeyOf?: boolean): string[];
  456. export declare function extractRuntimeEmits(ctx: TypeResolveContext): Set<string>;
  457. export declare const version: string;
  458. export declare const parseCache: Map<string, SFCParseResult>;
  459. export declare const errorMessages: Record<number, string>;
  460. export declare const walk: any;
  461. /**
  462. * @deprecated this is preserved to avoid breaking vite-plugin-vue < 5.0
  463. * with reactivityTransform: true. The desired behavior should be silently
  464. * ignoring the option instead of breaking.
  465. */
  466. export declare const shouldTransformRef: () => boolean;