compiler-sfc.d.ts 16 KB

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