TypeScript packager plugin for Parcel bundler that handles the packaging phase of TypeScript assets by combining them into bundles and managing source map references
npx @tessl/cli install tessl/npm-parcel--packager-ts@2.15.0@parcel/packager-ts is a TypeScript packager plugin for Parcel that handles the final packaging phase of TypeScript compilation. It processes single-asset TypeScript bundles by extracting compiled JavaScript code, managing source maps, and appending proper source map references for debugging support.
This plugin is typically not imported directly by users, but rather used internally by Parcel:
import {Packager} from '@parcel/plugin';For advanced plugin development scenarios:
import type {
PackageContext,
PluginOptions,
PluginLogger,
PluginTracer,
BundleGraph,
NamedBundle,
BundleResult
} from '@parcel/types';For direct usage (advanced scenarios only):
const TSPackager = require('@parcel/packager-ts');
// TSPackager is a configured Packager instance, not a classThis plugin operates automatically within Parcel's build pipeline when processing TypeScript files. It does not require manual configuration or direct invocation by end users.
// Your TypeScript source file
export function greet(name: string): string {
return `Hello, ${name}!`;
}
// Parcel processes this through the TypeScript packager automaticallyThe @parcel/packager-ts plugin is part of Parcel's packaging phase, which occurs after transformation and optimization. The packaging phase combines processed assets into final bundles.
Plugin Lifecycle:
loadConfig and loadBundleConfig methods can load plugin-specific configurationpackage method processes bundles containing TypeScript assetsIntegration Points:
Processes TypeScript bundles during Parcel's packaging phase, converting compiled TypeScript assets into final JavaScript bundles with proper source map integration.
/**
* Main packaging function that processes TypeScript bundles
* @param context - Complete packaging context with bundle, configuration, and utilities
* @returns Promise resolving to packaged bundle result with contents and source map
*/
async function package(context: PackageContext): Promise<BundleResult>;
interface PackageContext {
/** The bundle containing TypeScript assets to process */
bundle: NamedBundle;
/** Complete bundle graph for dependency resolution */
bundleGraph: BundleGraph<NamedBundle>;
/** Global Parcel options and configuration */
options: PluginOptions;
/** Plugin logger for diagnostics and debugging */
logger: PluginLogger;
/** Performance tracing utilities */
tracer: PluginTracer;
/** Plugin-specific configuration (from loadConfig) */
config: any;
/** Bundle-specific configuration (from loadBundleConfig) */
bundleConfig: any;
/** Function to get contents of inline bundles */
getInlineBundleContents: (
bundle: Bundle,
bundleGraph: BundleGraph<NamedBundle>
) => Promise<{contents: Blob}>;
/** Function to generate source map references */
getSourceMapReference: (map: ?SourceMap) => Promise<?string>;
}The packaging process:
Individual asset processing within the bundle.
interface Asset {
/** Retrieves the compiled JavaScript code from the asset */
getCode(): Promise<string>;
/** Retrieves the source map associated with the asset */
getMap(): Promise<?SourceMap>;
}Core Parcel bundle interfaces used by the packager.
interface Bundle {
/** The bundle identifier */
+id: string;
/** The bundle type (e.g., 'js') */
+type: string;
/** The target environment */
+env: Environment;
/** The bundle's target configuration */
+target: Target;
/** Whether the bundle needs a stable filename */
+needsStableName: ?boolean;
/** Controls bundle behavior (inline/isolated) */
+bundleBehavior: ?BundleBehavior;
/** Whether bundle can be split */
+isSplittable: ?boolean;
/** Placeholder for content hash */
+hashReference: string;
/** Returns entry assets executed when bundle loads */
getEntryAssets(): Array<Asset>;
/** Returns main entry asset providing bundle exports */
getMainEntry(): ?Asset;
/** Checks if bundle includes given asset */
hasAsset(Asset): boolean;
/** Checks if bundle includes given dependency */
hasDependency(Dependency): boolean;
/** Traverses all assets in the bundle */
traverseAssets<TContext>(
visit: GraphVisitor<Asset, TContext>,
startAsset?: Asset
): ?TContext;
/** Traverses assets and dependencies in bundle */
traverse<TContext>(
visit: GraphVisitor<BundleTraversable, TContext>
): ?TContext;
/** Returns hash of bundle contents */
getContentHash(): string;
}
interface NamedBundle extends Bundle {
/** Shortened bundle ID for runtime reference */
+publicId: string;
/** Bundle filename relative to target directory */
+name: string;
/** Display-friendly bundle name */
+displayName: string;
}
type BundleBehavior = 'inline' | 'isolated';
type GraphVisitor<TNode, TContext> = (
node: TNode,
context: TContext | null
) => TContext | null;
interface Environment {
/** Build context (e.g., 'browser', 'node') */
+context: string;
/** Target engines and versions */
+engines: {[string]: string};
/** Include node modules configuration */
+includeNodeModules: boolean | Array<string>;
/** Output format */
+outputFormat: string;
/** Source map configuration */
+sourceMap: ?SourceMapOptions;
}
interface Target {
/** Target name */
+name: string;
/** Distribution directory */
+distDir: FilePath;
/** Target environment */
+env: Environment;
/** Source glob patterns */
+source: string | Array<string>;
/** Location configuration */
+loc: ?SourceLocation;
}
interface SourceMapOptions {
/** Whether to generate source maps */
+enabled: boolean;
/** Include source maps inline in bundle */
+inline: boolean;
/** Source root path */
+sourceRoot?: string;
}
type FilePath = string;
type SourceLocation = {|
+filePath: FilePath,
+start: {| +line: number, +column: number |},
+end: {| +line: number, +column: number |},
|};Essential Parcel plugin interfaces used throughout the packaging system.
interface PluginOptions {
/** Build mode (development/production) */
+mode: BuildMode;
/** Parcel version */
+parcelVersion: string;
/** Environment variables */
+env: EnvMap;
/** Hot module replacement options */
+hmrOptions: ?HMROptions;
/** Development server options */
+serveOptions: ServerOptions | false;
/** Lazy bundling flag */
+shouldBuildLazily: boolean;
/** Auto-install dependencies flag */
+shouldAutoInstall: boolean;
/** Logging level */
+logLevel: LogLevel;
/** Project root directory */
+projectRoot: FilePath;
/** Cache directory */
+cacheDir: FilePath;
/** Input file system */
+inputFS: FileSystem;
/** Output file system */
+outputFS: FileSystem;
/** Package manager instance */
+packageManager: PackageManager;
/** Parcel instance ID */
+instanceId: string;
/** Detailed reporting options */
+detailedReport: ?DetailedReportOptions;
/** Feature flags */
+featureFlags: FeatureFlags;
}
interface PluginLogger {
/** Log verbose diagnostic messages */
verbose(diagnostic: DiagnosticWithoutOrigin | Array<DiagnosticWithoutOrigin>): void;
/** Log informational messages */
info(diagnostic: DiagnosticWithoutOrigin | Array<DiagnosticWithoutOrigin>): void;
/** Log general messages */
log(diagnostic: DiagnosticWithoutOrigin | Array<DiagnosticWithoutOrigin>): void;
/** Log warning messages */
warn(diagnostic: DiagnosticWithoutOrigin | Array<DiagnosticWithoutOrigin>): void;
/** Log error messages */
error(input: Diagnostifiable | DiagnosticWithoutOrigin | Array<DiagnosticWithoutOrigin>): void;
}
interface PluginTracer {
/** Whether tracing is enabled */
+enabled: boolean;
/** Create a performance measurement */
createMeasurement(
name: string,
category?: string,
argumentName?: string,
otherArgs?: {[key: string]: mixed}
): TraceMeasurement | null;
}
interface Config {
/** Whether this is source-level config */
+isSource: boolean;
/** Config search path */
+searchPath: FilePath;
/** Target environment */
+env: Environment;
/** Invalidate cache when file changes */
invalidateOnFileChange(FilePath): void;
/** Invalidate cache when file is created */
invalidateOnFileCreate(FileCreateInvalidation): void;
/** Invalidate cache when environment variable changes */
invalidateOnEnvChange(string): void;
/** Invalidate cache on startup */
invalidateOnStartup(): void;
/** Invalidate cache on build */
invalidateOnBuild(): void;
/** Add development dependency */
addDevDependency(DevDepOptions): void;
/** Set cache key */
setCacheKey(string): void;
/** Get configuration from files */
getConfig<T>(
filePaths: Array<FilePath>,
options?: {|
packageKey?: string,
parse?: boolean,
exclude?: boolean,
|}
): Promise<?ConfigResultWithFilePath<T>>;
/** Get configuration from specific search path */
getConfigFrom<T>(
searchPath: FilePath,
filePaths: Array<FilePath>,
options?: {|
packageKey?: string,
parse?: boolean,
exclude?: boolean,
|}
): Promise<?ConfigResultWithFilePath<T>>;
/** Get package.json */
getPackage(): Promise<?PackageJSON>;
}
type Blob = string | Buffer | Readable;
type BuildMode = 'development' | 'production';
type LogLevel = 'none' | 'error' | 'warn' | 'info' | 'verbose';The BundleGraph provides access to the complete dependency graph and bundle relationships.
interface BundleGraph<TBundle: Bundle> {
/** Get asset by ID */
getAssetById(id: string): Asset;
/** Get public ID for asset */
getAssetPublicId(asset: Asset): string;
/** Get all bundles */
getBundles(opts?: {|includeInline: boolean|}): Array<TBundle>;
/** Traverse bundle graph */
traverse<TContext>(
visit: GraphVisitor<BundleGraphTraversable, TContext>,
startAsset: ?Asset,
options?: {|skipUnusedDependencies?: boolean|}
): ?TContext;
/** Traverse bundles */
traverseBundles<TContext>(
visit: GraphVisitor<TBundle, TContext>,
startBundle: ?Bundle
): ?TContext;
/** Get bundle groups containing bundle */
getBundleGroupsContainingBundle(bundle: Bundle): Array<BundleGroup>;
/** Get bundles in bundle group */
getBundlesInBundleGroup(bundleGroup: BundleGroup): Array<TBundle>;
/** Get child bundles */
getChildBundles(bundle: Bundle): Array<TBundle>;
/** Get parent bundles */
getParentBundles(bundle: Bundle): Array<TBundle>;
/** Get dependencies for asset */
getDependencies(asset: Asset): Array<Dependency>;
/** Get incoming dependencies for asset */
getIncomingDependencies(asset: Asset): Array<Dependency>;
/** Get asset with dependency */
getAssetWithDependency(dep: Dependency): ?Asset;
/** Get resolved asset for dependency */
getResolvedAsset(dependency: Dependency, bundle: ?Bundle): ?Asset;
}The packager returns structured results containing the final bundle output.
interface BundleResult {
/** The final packaged contents as a Blob */
+contents: Blob;
/** Optional AST representation */
+ast?: AST;
/** Optional source map */
+map?: ?SourceMap;
/** Optional content type override */
+type?: string;
}Base interface for Parcel packager plugins.
class Packager {
/**
* Creates a new packager plugin instance
* @param opts - Packager configuration options
*/
constructor<ConfigType, BundleConfigType>(opts: PackagerOpts<ConfigType, BundleConfigType>);
}
interface PackagerOpts<ConfigType, BundleConfigType> {
/** Optional configuration loader executed during plugin initialization */
loadConfig?: (context: LoadConfigContext) => Promise<ConfigType>;
/** Optional bundle-specific configuration loader */
loadBundleConfig?: (context: LoadBundleConfigContext) => Promise<BundleConfigType>;
/** Main packaging function (required) */
package(context: PackageContext<ConfigType, BundleConfigType>): Promise<BundleResult | BundleResult[]>;
}
interface LoadConfigContext {
/** Configuration management utilities */
config: Config;
/** Global Parcel options */
options: PluginOptions;
/** Plugin logger instance */
logger: PluginLogger;
/** Performance tracer */
tracer: PluginTracer;
}
interface LoadBundleConfigContext {
/** The specific bundle being configured */
bundle: NamedBundle;
/** Complete bundle graph */
bundleGraph: BundleGraph<NamedBundle>;
/** Configuration management utilities */
config: Config;
/** Global Parcel options */
options: PluginOptions;
/** Plugin logger instance */
logger: PluginLogger;
/** Performance tracer */
tracer: PluginTracer;
}The packager performs validation and will throw errors in specific scenarios:
When source maps are available, the packager automatically appends source map references using standard JavaScript comment syntax:
// Generated bundle content
export function greet(name) { return `Hello, ${name}!`; }
//# sourceMappingURL=bundle.js.mapThis packager is automatically registered by Parcel for TypeScript file processing. Manual registration is not required for typical usage.