UNPKG

17.8 kBTypeScriptView Raw
1// Type definitions for @babel/core 7.0
2// Project: https://github.com/babel/babel/tree/master/packages/babel-core
3// Definitions by: Troy Gerwien <https://github.com/yortus>
4// Marvin Hagemeister <https://github.com/marvinhagemeister>
5// Melvin Groenhoff <https://github.com/mgroenhoff>
6// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
7// TypeScript Version: 2.8
8
9import { GeneratorOptions } from "@babel/generator";
10import traverse, { Visitor, NodePath } from "@babel/traverse";
11import template from "@babel/template";
12import * as t from "@babel/types";
13import { BabylonOptions } from "babylon";
14
15export {
16 BabylonOptions,
17 GeneratorOptions,
18 t as types,
19 template,
20 traverse,
21 Visitor
22};
23
24export type Node = t.Node;
25export type ParseResult = t.File | t.Program;
26export const version: string;
27
28export interface TransformOptions {
29 /**
30 * Include the AST in the returned object
31 *
32 * Default: `false`
33 */
34 ast?: boolean | null;
35
36 /**
37 * Attach a comment after all non-user injected code
38 *
39 * Default: `null`
40 */
41 auxiliaryCommentAfter?: string | null;
42
43 /**
44 * Attach a comment before all non-user injected code
45 *
46 * Default: `null`
47 */
48 auxiliaryCommentBefore?: string | null;
49
50 /**
51 * Specify the "root" folder that defines the location to search for "babel.config.js", and the default folder to allow `.babelrc` files inside of.
52 *
53 * Default: `"."`
54 */
55 root?: string | null;
56
57 /**
58 * The config file to load Babel's config from. Defaults to searching for "babel.config.js" inside the "root" folder. `false` will disable searching for config files.
59 *
60 * Default: `undefined`
61 */
62 configFile?: string | false | null;
63
64 /**
65 * Specify whether or not to use .babelrc and
66 * .babelignore files.
67 *
68 * Default: `true`
69 */
70 babelrc?: boolean | null;
71
72 /**
73 * Specify which packages should be search for .babelrc files when they are being compiled. `true` to always search, or a path string or an array of paths to packages to search
74 * inside of. Defaults to only searching the "root" package.
75 *
76 * Default: `(root)`
77 */
78 babelrcRoots?: true | string | string[] | null;
79
80 /**
81 * Defaults to environment variable `BABEL_ENV` if set, or else `NODE_ENV` if set, or else it defaults to `"development"`
82 *
83 * Default: env vars
84 */
85 envName?: string | null;
86
87 /**
88 * Enable code generation
89 *
90 * Default: `true`
91 */
92 code?: boolean | null;
93
94 /**
95 * Output comments in generated output
96 *
97 * Default: `true`
98 */
99 comments?: boolean | null;
100
101 /**
102 * Do not include superfluous whitespace characters and line terminators. When set to `"auto"` compact is set to `true` on input sizes of >500KB
103 *
104 * Default: `"auto"`
105 */
106 compact?: boolean | "auto" | null;
107
108 /**
109 * The working directory that Babel's programmatic options are loaded relative to.
110 *
111 * Default: `"."`
112 */
113 cwd?: string | null;
114
115 /**
116 * This is an object of keys that represent different environments. For example, you may have: `{ env: { production: { \/* specific options *\/ } } }`
117 * which will use those options when the `envName` is `production`
118 *
119 * Default: `{}`
120 */
121 env?: { [index: string]: TransformOptions | null | undefined; } | null;
122
123 /**
124 * A path to a `.babelrc` file to extend
125 *
126 * Default: `null`
127 */
128 extends?: string | null;
129
130 /**
131 * Filename for use in errors etc
132 *
133 * Default: `"unknown"`
134 */
135 filename?: string | null;
136
137 /**
138 * Filename relative to `sourceRoot`
139 *
140 * Default: `(filename)`
141 */
142 filenameRelative?: string | null;
143
144 /**
145 * An object containing the options to be passed down to the babel code generator, @babel/generator
146 *
147 * Default: `{}`
148 */
149 generatorOpts?: GeneratorOptions | null;
150
151 /**
152 * Specify a custom callback to generate a module id with. Called as `getModuleId(moduleName)`. If falsy value is returned then the generated module id is used
153 *
154 * Default: `null`
155 */
156 getModuleId?: ((moduleName: string) => string | null | undefined) | null;
157
158 /**
159 * ANSI highlight syntax error code frames
160 *
161 * Default: `true`
162 */
163 highlightCode?: boolean | null;
164
165 /**
166 * Opposite to the `only` option. `ignore` is disregarded if `only` is specified
167 *
168 * Default: `null`
169 */
170 ignore?: string[] | null;
171
172 /**
173 * A source map object that the output source map will be based on
174 *
175 * Default: `null`
176 */
177 inputSourceMap?: object | null;
178
179 /**
180 * Should the output be minified (not printing last semicolons in blocks, printing literal string values instead of escaped ones, stripping `()` from `new` when safe)
181 *
182 * Default: `false`
183 */
184 minified?: boolean | null;
185
186 /**
187 * Specify a custom name for module ids
188 *
189 * Default: `null`
190 */
191 moduleId?: string | null;
192
193 /**
194 * If truthy, insert an explicit id for modules. By default, all modules are anonymous. (Not available for `common` modules)
195 *
196 * Default: `false`
197 */
198 moduleIds?: boolean | null;
199
200 /**
201 * Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions
202 *
203 * Default: `(sourceRoot)`
204 */
205 moduleRoot?: string | null;
206
207 /**
208 * A glob, regex, or mixed array of both, matching paths to **only** compile. Can also be an array of arrays containing paths to explicitly match. When attempting to compile
209 * a non-matching file it's returned verbatim
210 *
211 * Default: `null`
212 */
213 only?: string | RegExp | Array<string | RegExp> | null;
214
215 /**
216 * An object containing the options to be passed down to the babel parser, @babel/parser
217 *
218 * Default: `{}`
219 */
220 parserOpts?: BabylonOptions | null;
221
222 /**
223 * List of plugins to load and use
224 *
225 * Default: `[]`
226 */
227 plugins?: PluginItem[] | null;
228
229 /**
230 * List of presets (a set of plugins) to load and use
231 *
232 * Default: `[]`
233 */
234 presets?: PluginItem[] | null;
235
236 /**
237 * Retain line numbers. This will lead to wacky code but is handy for scenarios where you can't use source maps. (**NOTE**: This will not retain the columns)
238 *
239 * Default: `false`
240 */
241 retainLines?: boolean | null;
242
243 /**
244 * An optional callback that controls whether a comment should be output or not. Called as `shouldPrintComment(commentContents)`. **NOTE**: This overrides the `comment` option when used
245 *
246 * Default: `null`
247 */
248 shouldPrintComment?: ((commentContents: string) => boolean) | null;
249
250 /**
251 * Set `sources[0]` on returned source map
252 *
253 * Default: `(filenameRelative)`
254 */
255 sourceFileName?: string | null;
256
257 /**
258 * If truthy, adds a `map` property to returned output. If set to `"inline"`, a comment with a sourceMappingURL directive is added to the bottom of the returned code. If set to `"both"`
259 * then a `map` property is returned as well as a source map comment appended. **This does not emit sourcemap files by itself!**
260 *
261 * Default: `false`
262 */
263 sourceMaps?: boolean | "inline" | "both" | null;
264
265 /**
266 * The root from which all sources are relative
267 *
268 * Default: `(moduleRoot)`
269 */
270 sourceRoot?: string | null;
271
272 /**
273 * Indicate the mode the code should be parsed in. Can be one of "script", "module", or "unambiguous". `"unambiguous"` will make Babel attempt to guess, based on the presence of ES6
274 * `import` or `export` statements. Files with ES6 `import`s and `export`s are considered `"module"` and are otherwise `"script"`.
275 *
276 * Default: `("module")`
277 */
278 sourceType?: "script" | "module" | "unambiguous" | null;
279
280 /**
281 * An optional callback that can be used to wrap visitor methods. **NOTE**: This is useful for things like introspection, and not really needed for implementing anything. Called as
282 * `wrapPluginVisitorMethod(pluginAlias, visitorType, callback)`.
283 */
284 wrapPluginVisitorMethod?: ((pluginAlias: string, visitorType: "enter" | "exit", callback: (path: NodePath, state: any) => void) => (path: NodePath, state: any) => void) | null;
285}
286
287export type FileResultCallback = (err: Error | null, result: BabelFileResult | null) => any;
288
289/**
290 * Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST.
291 */
292export function transform(code: string, callback: FileResultCallback): void;
293
294/**
295 * Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST.
296 */
297export function transform(code: string, opts: TransformOptions | undefined, callback: FileResultCallback): void;
298
299/**
300 * Here for backward-compatibility. Ideally use `transformSync` if you want a synchronous API.
301 */
302export function transform(code: string, opts?: TransformOptions): BabelFileResult | null;
303
304/**
305 * Transforms the passed in code. Returning an object with the generated code, source map, and AST.
306 */
307export function transformSync(code: string, opts?: TransformOptions): BabelFileResult | null;
308
309/**
310 * Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST.
311 */
312export function transformAsync(code: string, opts?: TransformOptions): Promise<BabelFileResult | null>;
313
314/**
315 * Asynchronously transforms the entire contents of a file.
316 */
317export function transformFile(filename: string, callback: FileResultCallback): void;
318
319/**
320 * Asynchronously transforms the entire contents of a file.
321 */
322export function transformFile(filename: string, opts: TransformOptions | undefined, callback: FileResultCallback): void;
323
324/**
325 * Synchronous version of `babel.transformFile`. Returns the transformed contents of the `filename`.
326 */
327export function transformFileSync(filename: string, opts?: TransformOptions): BabelFileResult | null;
328
329/**
330 * Asynchronously transforms the entire contents of a file.
331 */
332export function transformFileAsync(filename: string, opts?: TransformOptions): Promise<BabelFileResult | null>;
333
334/**
335 * Given an AST, transform it.
336 */
337export function transformFromAst(ast: Node, code: string | undefined, callback: FileResultCallback): void;
338
339/**
340 * Given an AST, transform it.
341 */
342export function transformFromAst(ast: Node, code: string | undefined, opts: TransformOptions | undefined, callback: FileResultCallback): void;
343
344/**
345 * Here for backward-compatibility. Ideally use ".transformSync" if you want a synchronous API.
346 */
347export function transformFromAstSync(ast: Node, code?: string, opts?: TransformOptions): BabelFileResult | null;
348
349/**
350 * Given an AST, transform it.
351 */
352export function transformFromAstSync(ast: Node, code?: string, opts?: TransformOptions): Promise<BabelFileResult | null>;
353
354// A babel plugin is a simple function which must return an object matching
355// the following interface. Babel will throw if it finds unknown properties.
356// The list of allowed plugin keys is here:
357// https://github.com/babel/babel/blob/4e50b2d9d9c376cee7a2cbf56553fe5b982ea53c/packages/babel-core/src/config/option-manager.js#L71
358export interface PluginObj<S = {}> {
359 name?: string;
360 manipulateOptions?(opts: any, parserOpts: any): void;
361 pre?(this: S, state: any): void;
362 visitor: Visitor<S>;
363 post?(this: S, state: any): void;
364 inherits?: any;
365}
366
367export interface BabelFileResult {
368 ast?: Node | null;
369 code?: string | null;
370 ignored?: boolean;
371 map?: {
372 version: number;
373 sources: string[];
374 names: string[];
375 sourceRoot?: string;
376 sourcesContent?: string[];
377 mappings: string;
378 file: string;
379 } | null;
380 metadata?: BabelFileMetadata;
381}
382
383export interface BabelFileMetadata {
384 usedHelpers: string[];
385 marked: Array<{
386 type: string;
387 message: string;
388 loc: object;
389 }>;
390 modules: BabelFileModulesMetadata;
391}
392
393export interface BabelFileModulesMetadata {
394 imports: object[];
395 exports: {
396 exported: object[];
397 specifiers: object[];
398 };
399}
400
401export type FileParseCallback = (err: Error | null, result: ParseResult | null) => any;
402
403/**
404 * Given some code, parse it using Babel's standard behavior.
405 * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
406 */
407export function parse(code: string, callback: FileParseCallback): void;
408
409/**
410 * Given some code, parse it using Babel's standard behavior.
411 * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
412 */
413export function parse(code: string, options: TransformOptions | undefined, callback: FileParseCallback): void;
414
415/**
416 * Given some code, parse it using Babel's standard behavior.
417 * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
418 */
419export function parse(code: string, options?: TransformOptions): ParseResult | null;
420
421/**
422 * Given some code, parse it using Babel's standard behavior.
423 * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
424 */
425export function parseSync(code: string, options?: TransformOptions): ParseResult | null;
426
427/**
428 * Given some code, parse it using Babel's standard behavior.
429 * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
430 */
431export function parseAsync(code: string, options?: TransformOptions): Promise<ParseResult | null>;
432
433/**
434 * Resolve Babel's options fully, resulting in an options object where:
435 *
436 * * opts.plugins is a full list of Plugin instances.
437 * * opts.presets is empty and all presets are flattened into opts.
438 * * It can be safely passed back to Babel. Fields like babelrc have been set to false so that later calls to Babel
439 * will not make a second attempt to load config files.
440 *
441 * Plugin instances aren't meant to be manipulated directly, but often callers will serialize this opts to JSON to
442 * use it as a cache key representing the options Babel has received. Caching on this isn't 100% guaranteed to
443 * invalidate properly, but it is the best we have at the moment.
444 */
445export function loadOptions(options?: TransformOptions): object | null;
446
447/**
448 * To allow systems to easily manipulate and validate a user's config, this function resolves the plugins and
449 * presets and proceeds no further. The expectation is that callers will take the config's .options, manipulate it
450 * as then see fit and pass it back to Babel again.
451 *
452 * * `babelrc: string | void` - The path of the `.babelrc` file, if there was one.
453 * * `babelignore: string | void` - The path of the `.babelignore` file, if there was one.
454 * * `options: ValidatedOptions` - The partially resolved options, which can be manipulated and passed back
455 * to Babel again.
456 * * `plugins: Array<ConfigItem>` - See below.
457 * * `presets: Array<ConfigItem>` - See below.
458 * * It can be safely passed back to Babel. Fields like `babelrc` have been set to false so that later calls to
459 * Babel will not make a second attempt to load config files.
460 *
461 * `ConfigItem` instances expose properties to introspect the values, but each item should be treated as
462 * immutable. If changes are desired, the item should be removed from the list and replaced with either a normal
463 * Babel config value, or with a replacement item created by `babel.createConfigItem`. See that function for
464 * information about `ConfigItem` fields.
465 */
466export function loadPartialConfig(options?: TransformOptions): Readonly<PartialConfig> | null;
467
468export interface PartialConfig {
469 options: TransformOptions;
470 babelrc?: string;
471 babelignore?: string;
472 config?: string;
473}
474
475export interface ConfigItem {
476 /**
477 * The name that the user gave the plugin instance, e.g. `plugins: [ ['env', {}, 'my-env'] ]`
478 */
479 name?: string;
480
481 /**
482 * The resolved value of the plugin.
483 */
484 value: object | ((...args: any[]) => any);
485
486 /**
487 * The options object passed to the plugin.
488 */
489 options?: object | false;
490
491 /**
492 * The path that the options are relative to.
493 */
494 dirname: string;
495
496 /**
497 * Information about the plugin's file, if Babel knows it.
498 * *
499 */
500 file?: {
501 /**
502 * The file that the user requested, e.g. `"@babel/env"`
503 */
504 request: string;
505
506 /**
507 * The full path of the resolved file, e.g. `"/tmp/node_modules/@babel/preset-env/lib/index.js"`
508 */
509 resolved: string;
510 } | null;
511}
512
513export type PluginOptions = object | undefined | false;
514
515export type PluginTarget = string | object | ((...args: any[]) => any);
516
517export type PluginItem = ConfigItem | PluginObj<any> | PluginTarget | [PluginTarget, PluginOptions] | [PluginTarget, PluginOptions, string | undefined];
518
519export interface CreateConfigItemOptions {
520 dirname?: string;
521 type?: "preset" | "plugin";
522}
523
524/**
525 * Allows build tooling to create and cache config items up front. If this function is called multiple times for a
526 * given plugin, Babel will call the plugin's function itself multiple times. If you have a clear set of expected
527 * plugins and presets to inject, pre-constructing the config items would be recommended.
528 */
529export function createConfigItem(value: PluginTarget | [PluginTarget, PluginOptions] | [PluginTarget, PluginOptions, string | undefined], options?: CreateConfigItemOptions): ConfigItem;
530
531export as namespace babel;
532
\No newline at end of file