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, config, logger, resolve, options }) {
// ...
return [asset];
},
async generate({ asset, ast, resolve, options }) {
// ...
return { code, map };
}
});
¶ Relevant API
DependencyOptions parcel/packages/core/types/index.js:465
Usen when creating a Dependency, see that.
type DependencyOptions = {|
+specifier: DependencySpecifier,
The specifier used to resolve the dependency.
+specifierType: SpecifierType,
How the specifier should be interpreted.
- esm: An ES module specifier. It is parsed as a URL, but bare specifiers are treated as node_modules.
- commonjs: A CommonJS specifier. It is not parsed as a URL.
- url: A URL that works as in a browser. Bare specifiers are treated as relative URLs.
- custom: A custom specifier. Must be handled by a custom resolver plugin.
+priority?: DependencyPriority,
When the dependency should be loaded.
- sync: The dependency should be resolvable synchronously. The resolved asset will be placed in the same bundle as the parent, or another bundle that's already on the page.
- parallel: The dependency should be placed in a separate bundle that's loaded in parallel with the current bundle.
- lazy: The dependency should be placed in a separate bundle that's loaded later.
Default value: 'sync'
+bundleBehavior?: BundleBehavior,
Controls the behavior of the bundle the resolved asset is placed into. Use in combination with priority
to determine when the bundle is loaded.
- inline: The resolved asset will be placed into a new inline bundle. Inline bundles are not written to a separate file, but embedded into the parent bundle.
- isolated: The resolved asset will be isolated from its parents in a separate bundle. Shared assets will be duplicated.
+needsStableName?: boolean,
When the dependency is a bundle entry (priority is "parallel" or "lazy"), this controls the naming
of that bundle. needsStableName
indicates that the name should be stable over time, even when the
content of the bundle changes. This is useful for entries that a user would manually enter the URL
for, as well as for things like service workers or RSS feeds, where the URL must remain consistent
over time.
+isOptional?: boolean,
Whether the dependency is optional. If the dependency cannot be resolved, this will not fail the build.
+loc?: SourceLocation,
The location within the source file where the dependency was found.
+env?: EnvironmentOptions,
The environment of the dependency.
+meta?: Meta,
Plugin-specific metadata for the dependency.
+pipeline?: string,
The pipeline defined in .parcelrc that the dependency should be processed with.
+resolveFrom?: FilePath,
The file path where the dependency should be resolved from. By default, this is the path of the source file where the dependency was specified.
+symbols?: $ReadOnlyMap<Symbol, {|
local: Symbol,
loc: ?SourceLocation,
isWeak: boolean,
meta?: Meta,
|}>,
The symbols within the resolved module that the source file depends on.
|}
Referenced by:
MutableAsset, TransformerResultDependency parcel/packages/core/types/index.js:531
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,
The id of the dependency.
+specifier: DependencySpecifier,
The specifier used to resolve the dependency.
+specifierType: SpecifierType,
How the specifier should be interpreted.
- esm: An ES module specifier. It is parsed as a URL, but bare specifiers are treated as node_modules.
- commonjs: A CommonJS specifier. It is not parsed as a URL.
- url: A URL that works as in a browser. Bare specifiers are treated as relative URLs.
- custom: A custom specifier. Must be handled by a custom resolver plugin.
+priority: DependencyPriority,
When the dependency should be loaded.
- sync: The dependency should be resolvable synchronously. The resolved asset will be placed in the same bundle as the parent, or another bundle that's already on the page.
- parallel: The dependency should be placed in a separate bundle that's loaded in parallel with the current bundle.
- lazy: The dependency should be placed in a separate bundle that's loaded later.
Default value: 'sync'
+bundleBehavior: ?BundleBehavior,
Controls the behavior of the bundle the resolved asset is placed into. Use in combination with priority
to determine when the bundle is loaded.
- inline: The resolved asset will be placed into a new inline bundle. Inline bundles are not written to a separate file, but embedded into the parent bundle.
- isolated: The resolved asset will be isolated from its parents in a separate bundle. Shared assets will be duplicated.
+needsStableName: boolean,
When the dependency is a bundle entry (priority is "parallel" or "lazy"), this controls the naming
of that bundle. needsStableName
indicates that the name should be stable over time, even when the
content of the bundle changes. This is useful for entries that a user would manually enter the URL
for, as well as for things like service workers or RSS feeds, where the URL must remain consistent
over time.
+isOptional: boolean,
Whether the dependency is optional. If the dependency cannot be resolved, this will not fail the build.
+isEntry: boolean,
Whether the dependency is an entry.
+loc: ?SourceLocation,
The location within the source file where the dependency was found.
+env: Environment,
The environment of the dependency.
+meta: Meta,
Plugin-specific metadata for the dependency.
+target: ?Target,
If this is an entry, this is the target that is associated with that entry.
+sourceAssetId: ?string,
The id of the asset with this dependency.
+sourcePath: ?FilePath,
The file path of the asset with this dependency.
+sourceAssetType: ?string,
The type of the asset that referenced this dependency.
+resolveFrom: ?FilePath,
The file path where the dependency should be resolved from. By default, this is the path of the source file where the dependency was specified.
+pipeline: ?string,
The pipeline defined in .parcelrc that the dependency should be processed with.
+symbols: MutableDependencySymbols,
}
Referenced by:
BaseAsset, Bundle, BundleGraph, BundleGraphTraversable, BundleTraversable, DependencyOptions, DependencySpecifier, MutableBundleGraph, Resolver, ResolvingProgressEvent, RuntimeAssetASTGenerator parcel/packages/core/types/index.js:610
type ASTGenerator = {|
type: string,
version: Semver,
|}
Referenced by:
BaseAssetBaseAsset parcel/packages/core/types/index.js:623
An asset represents a file or part of a file. It may represent any data type, including source code,
binary data, etc. Assets may exist in the file system or may be virtual.
interface BaseAsset {
+id: string,
The id of the asset.
+fs: FileSystem,
The file system where the source is located.
+filePath: FilePath,
The file path of the asset.
+type: string,
The asset's type. This initially corresponds to the source file extension, but it may be changed during transformation.
+query: QueryParameters,
The transformer options for the asset from the dependency query string.
+env: Environment,
The environment of the asset.
+isSource: boolean,
Whether this asset is part of the project, and not an external dependency (e.g. in node_modules). This indicates that transformation using the project's configuration should be applied.
+meta: Meta,
Plugin-specific metadata for the asset.
+bundleBehavior: ?BundleBehavior,
Controls which bundle the asset is placed into.
- inline: The asset will be placed into a new inline bundle. Inline bundles are not written to a separate file, but embedded into the parent bundle.
- isolated: The asset will be isolated from its parents in a separate bundle. Shared assets will be duplicated.
+isBundleSplittable: boolean,
If the asset is used as a bundle entry, this controls whether that bundle can be split into multiple, or whether all of the dependencies must be placed in a single bundle.
+sideEffects: boolean,
Whether this asset can be omitted if none of its exports are being used. This is initially set by the resolver, but can be overridden by transformers.
+uniqueKey: ?string,
When a transformer returns multiple assets, it can give them unique keys to identify them. This can be used to find assets during packaging, or to create dependencies between multiple assets returned by a transformer by using the unique key as the dependency specifier.
+astGenerator: ?ASTGenerator,
The type of the AST.
+pipeline: ?string,
The pipeline defined in .parcelrc that the asset should be processed with.
+symbols: AssetSymbols,
The symbols that the asset exports.
getAST(): Promise<?AST>,
Returns the current AST.
getCode(): Promise<string>,
Returns the asset contents as a string.
getBuffer(): Promise<Buffer>,
Returns the asset contents as a buffer.
getStream(): Readable,
Returns the asset contents as a stream.
getMap(): Promise<?SourceMap>,
Returns the source map for the asset, if available.
getMapBuffer(): Promise<?Buffer>,
Returns a buffer representation of the source map, if available.
getDependencies(): $ReadOnlyArray<Dependency>,
Returns a list of dependencies for the asset.
}
Referenced by:
Asset, MutableAsset, ResolveResultMutableAsset parcel/packages/core/types/index.js:696
A mutable Asset, available during transformation.
interface MutableAsset extends BaseAsset {
type: string,
The asset's type. This initially corresponds to the source file extension, but it may be changed during transformation.
bundleBehavior: ?BundleBehavior,
Controls which bundle the asset is placed into.
- inline: The asset will be placed into a new inline bundle. Inline bundles are not written to a separate file, but embedded into the parent bundle.
- isolated: The asset will be isolated from its parents in a separate bundle. Shared assets will be duplicated.
isBundleSplittable: boolean,
If the asset is used as a bundle entry, this controls whether that bundle can be split into multiple, or whether all of the dependencies must be placed in a single bundle.
Default value:
sideEffects: boolean,
Whether this asset can be omitted if none of its exports are being used. This is initially set by the resolver, but can be overridden by transformers.
+symbols: MutableAssetSymbols,
The symbols that the asset exports.
addDependency(DependencyOptions): string,
Adds a dependency to the asset.
addURLDependency(url: string, opts: $Shape<DependencyOptions>): string,
Adds a url dependency to the asset. This is a shortcut for addDependency that sets the specifierType to 'url' and priority to 'lazy'.
invalidateOnFileChange(FilePath): void,
Invalidates the transformation when the given file is modified or deleted.
invalidateOnFileCreate(FileCreateInvalidation): void,
Invalidates the transformation when matched files are created.
invalidateOnEnvChange(string): void,
Invalidates the transformation when the given environment variable changes.
setCode(string): void,
Sets the asset contents as a string.
setBuffer(Buffer): void,
Sets the asset contents as a buffer.
setStream(Readable): void,
Sets the asset contents as a stream.
setAST(AST): void,
Returns whether the AST has been modified.
isASTDirty(): boolean,
Sets the asset's AST.
setMap(?SourceMap): void,
Sets the asset's source map.
setEnvironment(opts: EnvironmentOptions): void,
}
Referenced by:
TransformerAsset parcel/packages/core/types/index.js:756
An immutable Asset, available after transformation.
interface Asset extends BaseAsset {
+stats: Stats,
Statistics about the asset.
}
Referenced by:
BuildSuccessEvent, Bundle, BundleGraph, BundleGraphTraversable, BundleTraversable, CreateBundleOpts, DedicatedThreadValidator, MultiThreadValidator, MutableAsset, MutableBundleGraph, SymbolResolution, Transformer, TransformingProgressEventConfig parcel/packages/core/types/index.js:780
interface Config {
+isSource: boolean,
Whether this config is part of the project, and not an external dependency (e.g. in node_modules). This indicates that transformation using the project's configuration should be applied.
+searchPath: FilePath,
The path of the file to start searching for config from.
+env: Environment,
The environment
invalidateOnFileChange(FilePath): void,
Invalidates the config when the given file is modified or deleted.
invalidateOnFileCreate(FileCreateInvalidation): void,
Invalidates the config when matched files are created.
invalidateOnEnvChange(string): void,
Invalidates the config when the given environment variable changes.
invalidateOnStartup(): void,
Invalidates the config when Parcel restarts.
addDevDependency(DevDepOptions): void,
Adds a dev dependency to the config. If the dev dependency or any of its dependencies change, the config will be invalidated.
setCacheKey(string): void,
Sets the cache key for the config. By default, this is computed as a hash of the files passed to invalidateOnFileChange or loaded by getConfig. If none, then a hash of the result returned from loadConfig is used. This method can be used to override this behavior and explicitly control the cache key. This can be useful in cases where only part of a file is used to avoid unnecessary invalidations, or when the result is not hashable (i.e. contains non-serializable properties like functions).
getConfig<T>(filePaths: Array<FilePath>, options: ?{|
packageKey?: string,
parse?: boolean,
exclude?: boolean,
|}): Promise<?ConfigResultWithFilePath<T>>,
Searches for config files with the given names in all parent directories of the config's searchPath.
getConfigFrom<T>(searchPath: FilePath, filePaths: Array<FilePath>, options: ?{|
packageKey?: string,
parse?: boolean,
exclude?: boolean,
|}): Promise<?ConfigResultWithFilePath<T>>,
Searches for config files with the given names in all parent directories of the passed searchPath.
getPackage(): Promise<?PackageJSON>,
Finds the nearest package.json from the config's searchPath.
}
Referenced by:
Bundler, Namer, Optimizer, Packager, Runtime, TransformerGenerateOutput parcel/packages/core/types/index.js:851
type GenerateOutput = {|
+content: Blob,
+map?: ?SourceMap,
|}
Referenced by:
TransformerTransformerResult parcel/packages/core/types/index.js:865
Transformers can return multiple result objects to create new assets.
For example, a file may contain multiple parts of different types,
which should be processed by their respective transformation pipelines.
type TransformerResult = {|
+type: string,
The asset's type.
+content?: ?Blob,
The content of the asset. Either content or an AST is required.
+ast?: ?AST,
+map?: ?SourceMap,
The source map for the asset.
+dependencies?: $ReadOnlyArray<DependencyOptions>,
The dependencies of the asset.
+env?: EnvironmentOptions,
The environment of the asset. The options are merged with the input asset's environment.
+bundleBehavior?: ?BundleBehavior,
Controls which bundle the asset is placed into.
- inline: The asset will be placed into a new inline bundle. Inline bundles are not written to a separate file, but embedded into the parent bundle.
- isolated: The asset will be isolated from its parents in a separate bundle. Shared assets will be duplicated.
+isBundleSplittable?: boolean,
If the asset is used as a bundle entry, this controls whether that bundle can be split into multiple, or whether all of the dependencies must be placed in a single bundle.
+meta?: Meta,
Plugin-specific metadata for the asset.
+pipeline?: ?string,
The pipeline defined in .parcelrc that the asset should be processed with.
+sideEffects?: boolean,
Whether this asset can be omitted if none of its exports are being used. This is initially set by the resolver, but can be overridden by transformers.
+symbols?: $ReadOnlyMap<Symbol, {|
local: Symbol,
loc: ?SourceLocation,
|}>,
The symbols that the asset exports.
+uniqueKey?: ?string,
When a transformer returns multiple assets, it can give them unique keys to identify them. This can be used to find assets during packaging, or to create dependencies between multiple assets returned by a transformer by using the unique key as the dependency specifier.
|}
Referenced by:
TransformerResolveFn parcel/packages/core/types/index.js:945
Type
type ResolveFn = (from: FilePath, to: string) => Promise<FilePath>;
Referenced by:
TransformerTransformer parcel/packages/core/types/index.js:1012
The methods for a transformer plugin.
type Transformer<ConfigType> = {|
loadConfig?: ({|
config: Config,
options: PluginOptions,
logger: PluginLogger,
|}) => Promise<ConfigType> | ConfigType,
canReuseAST?: ({|
ast: AST,
options: PluginOptions,
logger: PluginLogger,
|}) => boolean,
Whether an AST from a previous transformer can be reused (to prevent double-parsing)
parse?: ({|
asset: Asset,
config: ConfigType,
resolve: ResolveFn,
options: PluginOptions,
logger: PluginLogger,
|}) => Async<?AST>,
Parse the contents into an ast
transform({|
asset: MutableAsset,
config: ConfigType,
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
|}