Transformer
A plugin type: Convert an asset (into another asset)
Transformers transform single assets as they are discovered and added to the asset graph. They mostly call out to different compilers and preprocessors.
import { Transformer } from "@parcel/plugin";
export default new Transformer({
  async canReuseAST({ ast, options, logger }) {
    return false;
  }
  async loadConfig({ config, options, logger }) {
    // ...
    return config;
  },
  async parse({ asset, config, logger, resolve, options }) {
    // ...
    return ast;
  },
  async transform({ asset, ast, config, logger, resolve, options }) {
    // ...
    return [asset];
  },
  async generate({ asset, ast, resolve, options }) {
    // ...
    return { code, map };
  },
  async postProcess({assets, config, options, resolve, logger}) {
    return assets;
  }
});
¶ Relevant API
DependencyOptions parcel/packages/core/types/index.js:409
Usen when creating a Dependency, see that.
type DependencyOptions = {|
  +moduleSpecifier: ModuleSpecifier,
  +isAsync?: boolean,
  +isEntry?: boolean,
Is merged with the environment of the importer
  +isOptional?: boolean,
  +isURL?: boolean,
  +isIsolated?: boolean,
  +loc?: SourceLocation,
  +env?: EnvironmentOpts,
  +meta?: Meta,
  +target?: Target,
  +symbols?: $ReadOnlyMap<Symbol, {|
    local: Symbol,
    loc: ?SourceLocation,
    isWeak: boolean,
  |}>,
|}
Referenced by:
MutableAsset, TransformerResultDependency parcel/packages/core/types/index.js:433
A Dependency denotes a connection between two assets (likely some effect from the importee is expected - be it a side effect or a value is being imported).
interface Dependency {
  +id: string,
  +moduleSpecifier: ModuleSpecifier,
E.g. "lodash" in 
import {add} from "lodash";
  +isAsync: boolean,
  +isEntry: ?boolean,
Whether this should become a entry in a bundle.
  +isOptional: boolean,
Whether a failed resolution should not cause a build error.
  +isURL: boolean,
Whether an URL is expected (rather than the language-specific behaviour).
  +isIsolated: boolean,
  +loc: ?SourceLocation,
Used for error messages, the code location that caused this dependency.
  +env: Environment,
  +meta: Meta,
  +target: ?Target,
  +sourceAssetId: ?string,
Used for error messages, the importer.
  +sourcePath: ?string,
Used for error messages, the importer.
  +pipeline: ?string,
a named pipeline (if the 
moduleSpecifier didn't specify one).
  +symbols: MutableDependencySymbols,
}
Referenced by:
BaseAsset, BundleGraph, BundleTraversable, BundlerBundleGraphTraversable, DependencyOptions, ModuleSpecifier, MutableBundleGraph, Resolver, ResolvingProgressEvent, RuntimeAssetASTGenerator parcel/packages/core/types/index.js:470
type ASTGenerator = {|
  type: string,
  version: string,
|}
Referenced by:
BaseAssetBaseAsset parcel/packages/core/types/index.js:480
An asset (usually represents one source file).
interface BaseAsset {
  +env: Environment,
  +fs: FileSystem,
The file system where the source is located.
  +filePath: FilePath,
  +query: QueryParameters,
  +id: string,
  +meta: Meta,
  +isIsolated: boolean,
  +isInline: boolean,
Whether this asset will/should later be inserted back into the importer.
  +isSplittable: ?boolean,
  +isSource: boolean,
Whether this is asset is part of the users project (and not of an external dependencies) and should be transpiled.
  +type: string,
Usually corresponds to the file extension
  +sideEffects: boolean,
Whether this asset can be omitted if none if it's exports are being used (set by ResolveResult)
  +uniqueKey: ?string,
Inline assets inheirit the parent's 
id, making it not be enough for a unique identification
(this could be a counter that is unique per asset)
  +astGenerator: ?ASTGenerator,
The type of the AST.
  +pipeline: ?string,
  +symbols: AssetSymbols,
a 
Map<export name, name of binding>
  getAST(): Promise<?AST>,
  getCode(): Promise<string>,
Returns to current source code. See notes in MutableAsset.
  getBuffer(): Promise<Buffer>,
Returns the contents as a buffer.
  getStream(): Readable,
Returns the contents as a stream.
  getMap(): Promise<?SourceMap>,
Returns the sourcemap (if existent).
  getMapBuffer(): Promise<?Buffer>,
A buffer representation of the sourcemap (if existent).
  getDependencies(): $ReadOnlyArray<Dependency>,
  getConfig(filePaths: Array<FilePath>, options: ?{|
    packageKey?: string,
    parse?: boolean,
  |}): Promise<ConfigResult | null>,
Used to load config files, (looks in every parent folder until a module root) for the specified filenames. 
packageKey can be used to also check pkg#[packageKey].
  getPackage(): Promise<PackageJSON | null>,
Returns the package.json this file belongs to.
}
Referenced by:
Asset, MutableAsset, ResolveResult, TransformerResultMutableAsset parcel/packages/core/types/index.js:541
A somewhat modifiable version of BaseAsset (for transformers)
interface MutableAsset extends BaseAsset {
  isIsolated: boolean,
  isInline: boolean,
  isSplittable: ?boolean,
  type: string,
  addDependency(dep: DependencyOptions): string,
  addIncludedFile(filePath: FilePath): void,
  addURLDependency(url: string, opts: $Shape<DependencyOptions>): string,
  invalidateOnEnvChange(env: string): void,
  +symbols: MutableAssetSymbols,
  isASTDirty(): boolean,
  getAST(): Promise<?AST>,
Returns 
null if there is no AST.
  setAST(AST): void,
  setBuffer(Buffer): void,
  setCode(string): void,
  getCode(): Promise<string>,
  setEnvironment(opts: EnvironmentOpts): void,
  setMap(?SourceMap): void,
  setStream(Readable): void,
}
Referenced by:
BaseAsset, TransformerAsset parcel/packages/core/types/index.js:570
interface Asset extends BaseAsset {
  getAST(): Promise<?AST>,
Throws if there is no AST.
  +stats: Stats,
}
Referenced by:
BaseAsset, BuildSuccessEvent, Bundle, BundleGraph, BundleTraversable, BundlerBundleGraphTraversable, CreateBundleOpts, DedicatedThreadValidator, MultiThreadValidator, MutableBundleGraph, SymbolResolution, Transformer, TransformingProgressEventConfig parcel/packages/core/types/index.js:580
interface Config {
  +isSource: boolean,
  +searchPath: FilePath,
  +result: ConfigResult,
  +env: Environment,
  +includedFiles: Set<FilePath>,
  setResult(result: ConfigResult): void,
  setResultHash(resultHash: string): void,
  addIncludedFile(filePath: FilePath): void,
  addDevDependency(name: PackageName, version?: Semver): void,
  setWatchGlob(glob: string): void,
  getConfigFrom(searchPath: FilePath, filePaths: Array<FilePath>, options: ?{|
    packageKey?: string,
    parse?: boolean,
    exclude?: boolean,
  |}): Promise<ConfigResultWithFilePath | null>,
  getConfig(filePaths: Array<FilePath>, options: ?{|
    packageKey?: string,
    parse?: boolean,
    exclude?: boolean,
  |}): Promise<ConfigResultWithFilePath | null>,
  getPackage(): Promise<PackageJSON | null>,
  shouldRehydrate(): void,
  shouldReload(): void,
  shouldInvalidateOnStartup(): void,
}
Referenced by:
TransformerGenerateOutput parcel/packages/core/types/index.js:623
type GenerateOutput = {|
  +content: Blob,
  +map?: ?SourceMap,
|}
Referenced by:
TransformerTransformerResult parcel/packages/core/types/index.js:634
Will be used to generate a new BaseAsset, see that.
type TransformerResult = {|
  +ast?: ?AST,
  +content?: ?Blob,
  +dependencies?: $ReadOnlyArray<DependencyOptions>,
  +env?: EnvironmentOpts,
  +filePath?: FilePath,
  +includedFiles?: $ReadOnlyArray<File>,
  +isInline?: boolean,
  +isIsolated?: boolean,
  +isSource?: boolean,
  +isSplittable?: boolean,
  +map?: ?SourceMap,
  +meta?: Meta,
  +pipeline?: ?string,
  +sideEffects?: boolean,
  +symbols?: $ReadOnlyMap<Symbol, {|
    local: Symbol,
    loc: ?SourceLocation,
  |}>,
  +type: string,
  +uniqueKey?: ?string,
|}
Referenced by:
TransformerResolveFn parcel/packages/core/types/index.js:659
Type
type ResolveFn = (from: FilePath, to: string) => Promise<FilePath>;
Referenced by:
TransformerTransformer parcel/packages/core/types/index.js:723
The methods for a transformer plugin.
type Transformer = {|
  loadConfig?: ({|
    config: Config,
    options: PluginOptions,
    logger: PluginLogger,
  |}) => Async<void>,
  preSerializeConfig?: ({|
    config: Config,
    options: PluginOptions,
  |}) => Async<void>,
  postDeserializeConfig?: ({|
    config: Config,
    options: PluginOptions,
    logger: PluginLogger,
  |}) => Async<void>,
  canReuseAST?: ({|
    ast: AST,
    options: PluginOptions,
    logger: PluginLogger,
  |}) => boolean,
Whether an AST from a previous transformer can be reused (to prevent double-parsing)
  parse?: ({|
    asset: MutableAsset,
    config: ?ConfigResult,
    resolve: ResolveFn,
    options: PluginOptions,
    logger: PluginLogger,
  |}) => Async<?AST>,
Parse the contents into an ast
  transform({|
    asset: MutableAsset,
    config: ?ConfigResult,
    resolve: ResolveFn,
    options: PluginOptions,
    logger: PluginLogger,
  |}): Async<Array<TransformerResult | MutableAsset>>,
Transform the asset and/or add new assets
  generate?: ({|
    asset: Asset,
    ast: AST,
    options: PluginOptions,
    logger: PluginLogger,
  |}) => Async<GenerateOutput>,
Stringify the AST
  postProcess?: ({|
    assets: Array<MutableAsset>,
    config: ?ConfigResult,
    resolve: ResolveFn,
    options: PluginOptions,
    logger: PluginLogger,
  |}) => Async<Array<TransformerResult>>,
|}