compiler-sfc.d.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. import * as _babel_types from '@babel/types';
  2. import { Statement, Expression, TSType, Program, Node, ObjectPattern, TSModuleDeclaration, TSPropertySignature, TSMethodSignature, TSCallSignatureDeclaration, TSFunctionType } from '@babel/types';
  3. import { CompilerOptions, CodegenResult, ParserOptions, RootNode, CompilerError, SourceLocation, ElementNode, BindingMetadata as BindingMetadata$1 } from '@vue/compiler-core';
  4. export { BindingMetadata, CompilerError, CompilerOptions, extractIdentifiers, generateCodeFrame, isInDestructureAssignment, isStaticProperty, walkIdentifiers } from '@vue/compiler-core';
  5. import { RawSourceMap } from 'source-map-js';
  6. import { ParserPlugin } from '@babel/parser';
  7. export { parse as babelParse } from '@babel/parser';
  8. import { Result, LazyResult } from 'postcss';
  9. import MagicString from 'magic-string';
  10. export { default as MagicString } from 'magic-string';
  11. export { shouldTransform as shouldTransformRef, transform as transformRef, transformAST as transformRefAST } from '@vue/reactivity-transform';
  12. export interface AssetURLTagConfig {
  13. [name: string]: string[];
  14. }
  15. export interface AssetURLOptions {
  16. /**
  17. * If base is provided, instead of transforming relative asset urls into
  18. * imports, they will be directly rewritten to absolute urls.
  19. */
  20. base?: string | null;
  21. /**
  22. * If true, also processes absolute urls.
  23. */
  24. includeAbsolute?: boolean;
  25. tags?: AssetURLTagConfig;
  26. }
  27. export interface TemplateCompiler {
  28. compile(template: string, options: CompilerOptions): CodegenResult;
  29. parse(template: string, options: ParserOptions): RootNode;
  30. }
  31. export interface SFCTemplateCompileResults {
  32. code: string;
  33. ast?: RootNode;
  34. preamble?: string;
  35. source: string;
  36. tips: string[];
  37. errors: (string | CompilerError)[];
  38. map?: RawSourceMap;
  39. }
  40. export interface SFCTemplateCompileOptions {
  41. source: string;
  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. * (**Experimental**) Enable macro `defineModel`
  118. * @default false
  119. */
  120. defineModel?: boolean;
  121. /**
  122. * (**Experimental**) Enable reactive destructure for `defineProps`
  123. * @default false
  124. */
  125. propsDestructure?: boolean;
  126. /**
  127. * File system access methods to be used when resolving types
  128. * imported in SFC macros. Defaults to ts.sys in Node.js, can be overwritten
  129. * to use a virtual file system for use in browsers (e.g. in REPLs)
  130. */
  131. fs?: {
  132. fileExists(file: string): boolean;
  133. readFile(file: string): string | undefined;
  134. };
  135. /**
  136. * (Experimental) Enable syntax transform for using refs without `.value` and
  137. * using destructured props with reactivity
  138. * @deprecated the Reactivity Transform proposal has been dropped. This
  139. * feature will be removed from Vue core in 3.4. If you intend to continue
  140. * using it, disable this and switch to the [Vue Macros implementation](https://vue-macros.sxzz.moe/features/reactivity-transform.html).
  141. */
  142. reactivityTransform?: boolean;
  143. }
  144. interface ImportBinding {
  145. isType: boolean;
  146. imported: string;
  147. local: string;
  148. source: string;
  149. isFromSetup: boolean;
  150. isUsedInTemplate: boolean;
  151. }
  152. /**
  153. * Compile `<script setup>`
  154. * It requires the whole SFC descriptor because we need to handle and merge
  155. * normal `<script>` + `<script setup>` if both are present.
  156. */
  157. export declare function compileScript(sfc: SFCDescriptor, options: SFCScriptCompileOptions): SFCScriptBlock;
  158. export interface SFCParseOptions {
  159. filename?: string;
  160. sourceMap?: boolean;
  161. sourceRoot?: string;
  162. pad?: boolean | 'line' | 'space';
  163. ignoreEmpty?: boolean;
  164. compiler?: TemplateCompiler;
  165. }
  166. export interface SFCBlock {
  167. type: string;
  168. content: string;
  169. attrs: Record<string, string | true>;
  170. loc: SourceLocation;
  171. map?: RawSourceMap;
  172. lang?: string;
  173. src?: string;
  174. }
  175. export interface SFCTemplateBlock extends SFCBlock {
  176. type: 'template';
  177. ast: ElementNode;
  178. }
  179. export interface SFCScriptBlock extends SFCBlock {
  180. type: 'script';
  181. setup?: string | boolean;
  182. bindings?: BindingMetadata$1;
  183. imports?: Record<string, ImportBinding>;
  184. scriptAst?: _babel_types.Statement[];
  185. scriptSetupAst?: _babel_types.Statement[];
  186. warnings?: string[];
  187. /**
  188. * Fully resolved dependency file paths (unix slashes) with imported types
  189. * used in macros, used for HMR cache busting in @vitejs/plugin-vue and
  190. * vue-loader.
  191. */
  192. deps?: string[];
  193. }
  194. export interface SFCStyleBlock extends SFCBlock {
  195. type: 'style';
  196. scoped?: boolean;
  197. module?: string | boolean;
  198. }
  199. export interface SFCDescriptor {
  200. filename: string;
  201. source: string;
  202. template: SFCTemplateBlock | null;
  203. script: SFCScriptBlock | null;
  204. scriptSetup: SFCScriptBlock | null;
  205. styles: SFCStyleBlock[];
  206. customBlocks: SFCBlock[];
  207. cssVars: string[];
  208. /**
  209. * whether the SFC uses :slotted() modifier.
  210. * this is used as a compiler optimization hint.
  211. */
  212. slotted: boolean;
  213. /**
  214. * compare with an existing descriptor to determine whether HMR should perform
  215. * a reload vs. re-render.
  216. *
  217. * Note: this comparison assumes the prev/next script are already identical,
  218. * and only checks the special case where <script setup lang="ts"> unused import
  219. * pruning result changes due to template changes.
  220. */
  221. shouldForceReload: (prevImports: Record<string, ImportBinding>) => boolean;
  222. }
  223. export interface SFCParseResult {
  224. descriptor: SFCDescriptor;
  225. errors: (CompilerError | SyntaxError)[];
  226. }
  227. export declare const parseCache: Map<string, SFCParseResult> & {
  228. max?: number | undefined;
  229. };
  230. export declare function parse(source: string, { sourceMap, filename, sourceRoot, pad, ignoreEmpty, compiler }?: SFCParseOptions): SFCParseResult;
  231. type PreprocessLang = 'less' | 'sass' | 'scss' | 'styl' | 'stylus';
  232. export interface SFCStyleCompileOptions {
  233. source: string;
  234. filename: string;
  235. id: string;
  236. scoped?: boolean;
  237. trim?: boolean;
  238. isProd?: boolean;
  239. inMap?: RawSourceMap;
  240. preprocessLang?: PreprocessLang;
  241. preprocessOptions?: any;
  242. preprocessCustomRequire?: (id: string) => any;
  243. postcssOptions?: any;
  244. postcssPlugins?: any[];
  245. /**
  246. * @deprecated use `inMap` instead.
  247. */
  248. map?: RawSourceMap;
  249. }
  250. /**
  251. * Aligns with postcss-modules
  252. * https://github.com/css-modules/postcss-modules
  253. */
  254. interface CSSModulesOptions {
  255. scopeBehaviour?: 'global' | 'local';
  256. generateScopedName?: string | ((name: string, filename: string, css: string) => string);
  257. hashPrefix?: string;
  258. localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly';
  259. exportGlobals?: boolean;
  260. globalModulePaths?: RegExp[];
  261. }
  262. export interface SFCAsyncStyleCompileOptions extends SFCStyleCompileOptions {
  263. isAsync?: boolean;
  264. modules?: boolean;
  265. modulesOptions?: CSSModulesOptions;
  266. }
  267. export interface SFCStyleCompileResults {
  268. code: string;
  269. map: RawSourceMap | undefined;
  270. rawResult: Result | LazyResult | undefined;
  271. errors: Error[];
  272. modules?: Record<string, string>;
  273. dependencies: Set<string>;
  274. }
  275. export declare function compileStyle(options: SFCStyleCompileOptions): SFCStyleCompileResults;
  276. export declare function compileStyleAsync(options: SFCAsyncStyleCompileOptions): Promise<SFCStyleCompileResults>;
  277. export declare function rewriteDefault(input: string, as: string, parserPlugins?: ParserPlugin[]): string;
  278. /**
  279. * Utility for rewriting `export default` in a script block into a variable
  280. * declaration so that we can inject things into it
  281. */
  282. export declare function rewriteDefaultAST(ast: Statement[], s: MagicString, as: string): void;
  283. type PropsDestructureBindings = Record<string, // public prop key
  284. {
  285. local: string;
  286. default?: Expression;
  287. }>;
  288. interface ModelDecl {
  289. type: TSType | undefined;
  290. options: string | undefined;
  291. identifier: string | undefined;
  292. }
  293. declare const enum BindingTypes {
  294. /**
  295. * returned from data()
  296. */
  297. DATA = "data",
  298. /**
  299. * declared as a prop
  300. */
  301. PROPS = "props",
  302. /**
  303. * a local alias of a `<script setup>` destructured prop.
  304. * the original is stored in __propsAliases of the bindingMetadata object.
  305. */
  306. PROPS_ALIASED = "props-aliased",
  307. /**
  308. * a let binding (may or may not be a ref)
  309. */
  310. SETUP_LET = "setup-let",
  311. /**
  312. * a const binding that can never be a ref.
  313. * these bindings don't need `unref()` calls when processed in inlined
  314. * template expressions.
  315. */
  316. SETUP_CONST = "setup-const",
  317. /**
  318. * a const binding that does not need `unref()`, but may be mutated.
  319. */
  320. SETUP_REACTIVE_CONST = "setup-reactive-const",
  321. /**
  322. * a const binding that may be a ref.
  323. */
  324. SETUP_MAYBE_REF = "setup-maybe-ref",
  325. /**
  326. * bindings that are guaranteed to be refs
  327. */
  328. SETUP_REF = "setup-ref",
  329. /**
  330. * declared by other options, e.g. computed, inject
  331. */
  332. OPTIONS = "options",
  333. /**
  334. * a literal constant, e.g. 'foo', 1, true
  335. */
  336. LITERAL_CONST = "literal-const"
  337. }
  338. type BindingMetadata = {
  339. [key: string]: BindingTypes | undefined;
  340. } & {
  341. __isScriptSetup?: boolean;
  342. __propsAliases?: Record<string, string>;
  343. };
  344. export declare class ScriptCompileContext {
  345. descriptor: SFCDescriptor;
  346. options: Partial<SFCScriptCompileOptions>;
  347. isJS: boolean;
  348. isTS: boolean;
  349. scriptAst: Program | null;
  350. scriptSetupAst: Program | null;
  351. source: string;
  352. filename: string;
  353. s: MagicString;
  354. startOffset: number | undefined;
  355. endOffset: number | undefined;
  356. scope?: TypeScope;
  357. globalScopes?: TypeScope[];
  358. userImports: Record<string, ImportBinding>;
  359. hasDefinePropsCall: boolean;
  360. hasDefineEmitCall: boolean;
  361. hasDefineExposeCall: boolean;
  362. hasDefaultExportName: boolean;
  363. hasDefaultExportRender: boolean;
  364. hasDefineOptionsCall: boolean;
  365. hasDefineSlotsCall: boolean;
  366. hasDefineModelCall: boolean;
  367. propsIdentifier: string | undefined;
  368. propsRuntimeDecl: Node | undefined;
  369. propsTypeDecl: Node | undefined;
  370. propsDestructureDecl: ObjectPattern | undefined;
  371. propsDestructuredBindings: PropsDestructureBindings;
  372. propsDestructureRestId: string | undefined;
  373. propsRuntimeDefaults: Node | undefined;
  374. emitsRuntimeDecl: Node | undefined;
  375. emitsTypeDecl: Node | undefined;
  376. emitIdentifier: string | undefined;
  377. modelDecls: Record<string, ModelDecl>;
  378. optionsRuntimeDecl: Node | undefined;
  379. bindingMetadata: BindingMetadata;
  380. helperImports: Set<string>;
  381. helper(key: string): string;
  382. /**
  383. * to be exposed on compiled script block for HMR cache busting
  384. */
  385. deps?: Set<string>;
  386. /**
  387. * cache for resolved fs
  388. */
  389. fs?: NonNullable<SFCScriptCompileOptions['fs']>;
  390. constructor(descriptor: SFCDescriptor, options: Partial<SFCScriptCompileOptions>);
  391. getString(node: Node, scriptSetup?: boolean): string;
  392. error(msg: string, node: Node, scope?: TypeScope): never;
  393. }
  394. /**
  395. * TypeResolveContext is compatible with ScriptCompileContext
  396. * but also allows a simpler version of it with minimal required properties
  397. * when resolveType needs to be used in a non-SFC context, e.g. in a babel
  398. * plugin. The simplest context can be just:
  399. * ```ts
  400. * const ctx: SimpleTypeResolveContext = {
  401. * filename: '...',
  402. * source: '...',
  403. * options: {},
  404. * error() {},
  405. * ast: []
  406. * }
  407. * ```
  408. */
  409. export type SimpleTypeResolveContext = Pick<ScriptCompileContext, 'source' | 'filename' | 'error' | 'options'> & Partial<Pick<ScriptCompileContext, 'scope' | 'globalScopes' | 'deps' | 'fs'>> & {
  410. ast: Statement[];
  411. };
  412. export type TypeResolveContext = ScriptCompileContext | SimpleTypeResolveContext;
  413. type Import = Pick<ImportBinding, 'source' | 'imported'>;
  414. interface WithScope {
  415. _ownerScope: TypeScope;
  416. }
  417. type ScopeTypeNode = Node & WithScope & {
  418. _ns?: TSModuleDeclaration & WithScope;
  419. };
  420. declare class TypeScope {
  421. filename: string;
  422. source: string;
  423. offset: number;
  424. imports: Record<string, Import>;
  425. types: Record<string, ScopeTypeNode>;
  426. declares: Record<string, ScopeTypeNode>;
  427. constructor(filename: string, source: string, offset?: number, imports?: Record<string, Import>, types?: Record<string, ScopeTypeNode>, declares?: Record<string, ScopeTypeNode>);
  428. resolvedImportSources: Record<string, string>;
  429. exportedTypes: Record<string, ScopeTypeNode>;
  430. exportedDeclares: Record<string, ScopeTypeNode>;
  431. }
  432. interface MaybeWithScope {
  433. _ownerScope?: TypeScope;
  434. }
  435. interface ResolvedElements {
  436. props: Record<string, (TSPropertySignature | TSMethodSignature) & {
  437. _ownerScope: TypeScope;
  438. }>;
  439. calls?: (TSCallSignatureDeclaration | TSFunctionType)[];
  440. }
  441. /**
  442. * Resolve arbitrary type node to a list of type elements that can be then
  443. * mapped to runtime props or emits.
  444. */
  445. export declare function resolveTypeElements(ctx: TypeResolveContext, node: Node & MaybeWithScope & {
  446. _resolvedElements?: ResolvedElements;
  447. }, scope?: TypeScope): ResolvedElements;
  448. /**
  449. * @private
  450. */
  451. export declare function registerTS(_ts: any): void;
  452. /**
  453. * @private
  454. */
  455. export declare function invalidateTypeCache(filename: string): void;
  456. export declare function inferRuntimeType(ctx: TypeResolveContext, node: Node & MaybeWithScope, scope?: TypeScope): string[];
  457. export declare const version: string;
  458. export declare const walk: any;