Plugin API for Parcel bundler - provides base classes for creating Parcel plugins including transformers, resolvers, bundlers, namers, runtimes, packagers, optimizers, compressors, reporters, and validators
67
The Runtime plugin injects runtime code into bundles for features like hot module replacement, dynamic imports, and environment-specific functionality. Runtimes provide the necessary code to support Parcel's advanced features at runtime.
Base class for creating runtime injection plugins.
/**
* Base class for runtime injection plugins
* @template T - Configuration type for this runtime
*/
export declare class Runtime<T> {
constructor(opts: RuntimeOpts<T>);
}
/**
* Runtime plugin configuration interface
* @template ConfigType - Type of configuration returned by loadConfig
*/
interface RuntimeOpts<ConfigType> {
/** Load configuration for this runtime */
loadConfig?: (args: {
config: Config;
options: PluginOptions;
logger: PluginLogger;
tracer: PluginTracer;
}) => Promise<ConfigType> | ConfigType;
/** Apply runtime code to a bundle (required) */
apply(args: {
bundle: NamedBundle;
bundleGraph: BundleGraph<NamedBundle>;
config: ConfigType;
options: PluginOptions;
logger: PluginLogger;
tracer: PluginTracer;
}): Promise<void | RuntimeAsset | Array<RuntimeAsset>>;
}/**
* Runtime asset to inject into bundles
*/
interface RuntimeAsset {
/** File path for the runtime asset */
filePath: FilePath;
/** Runtime code content */
code: string;
/** Dependency that triggered this runtime */
dependency?: Dependency;
/** Whether this should be treated as an entry */
isEntry?: boolean;
/** Environment options for this runtime */
env?: EnvironmentOptions;
/** Whether to replace the original resolution */
shouldReplaceResolution?: boolean;
}Usage Example:
import { Runtime } from "@parcel/plugin";
export default new Runtime({
// Apply runtime injection (required)
async apply({bundle, bundleGraph, options}) {
// Check if this bundle needs HMR runtime
if (options.mode === 'development' && options.hmrOptions) {
return {
filePath: '@parcel/runtime-hmr',
code: `
if (module.hot) {
module.hot.accept(() => {
window.location.reload();
});
}
`,
isEntry: false
};
}
// Check if bundle has dynamic imports
const hasDynamicImports = this.hasDynamicImports(bundle, bundleGraph);
if (hasDynamicImports) {
return {
filePath: '@parcel/runtime-dynamic-import',
code: this.generateDynamicImportRuntime(bundle, bundleGraph),
isEntry: false
};
}
},
hasDynamicImports(bundle, bundleGraph) {
const assets = bundleGraph.getBundleAssets(bundle);
return assets.some(asset =>
asset.getDependencies().some(dep => dep.isAsync)
);
},
generateDynamicImportRuntime(bundle, bundleGraph) {
return `
window.__parcel_require_loader__ = function(id) {
return import('./' + id + '.js');
};
`;
}
});Install with Tessl CLI
npx tessl i tessl/npm-parcel--plugindocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10