Skip to content
On this page

API Examples ​

This page demonstrates how to use Toypack.

run ​

Starts the bundling process.

ts
const bundleResult = await toypack.run();
ts
/**
 * @returns A Promise that resolves to the bundle result object.
 */
() => Promise<BundleResult>;

addOrUpdateAsset ​

Adds or updates an asset.

ts
toypack.addOrUpdateAsset("/index.js", "console.log(123);");
ts
/**
 * @param source The source of the asset to add or update.
 * @param content The content of the asset. If the asset doesn't exist yet,
 * this will default to an empty string.
 * @returns The added or updated asset.
 */
(source: string, content?: string | Blob) => Asset;

getAsset ​

Use this to retrieve an asset by source.

ts
const asset = toypack.getAsset("/index.js");
ts
/**
 * @param source The source of the asset to retrieve.
 * @returns The asset that matches the source or null if none.
 */
(source: string) => Asset | null;

removeAsset ​

Removes an asset by source.

ts
toypack.removeAsset("/index.js");
ts
/**
 * @param source The source of the asset to remove.
 */
(source: string) => void

removeDirectory ​

Removes a directory and returns all the assets the has been removed.

ts
toypack.removeDirectory("/src");
ts
/**
 * @param source The source of the directory to remove.
 * @returns An array containing the removed assets.
 */
(source: string) => Asset[]

moveAsset ​

Moves an asset to another source and returns the moved asset.

IMPORTANT NOTE

Under the hood, this method deletes and re-adds the asset. So the old asset object won't be equal to the new asset object.

ts
toypack.moveAsset("/index.js", "/src/index.js");
ts
/**
 * @param oldSource The source of the asset to move.
 * @param newSource The target source.
 * @returns The asset that has been moved or undefined if nothing is moved.
 */
(oldSource: string, newSource: string) => Asset | undefined;

moveDirectory ​

Moves a directory and returns all the assets that has been moved.

ts
toypack.moveDirectory("/src", "/");
ts
/**
 * @param oldSource The source of the directory to move.
 * @param newSource The target source.
 * @returns An array containing the descriptors of the assets that has
 * been moved.
 */
(oldSource: string, newSource: string) => {
   oldSource: string;
   newSource: string;
   asset: Asset;
}[]

getAssetSources ​

Use this to retrieve all of the existing assets' sources.

ts
import type { Asset } from "toypack/types";

const assetSources = toypack.getAssetSources();

// Get all assets
const assets: Record<string, Asset> = {};
for (const source of assetSources) {
   assets[source] = toypack.getAsset(source)!;
}
ts
/**
 * @returns An array containing the sources of the existing assets.
 */
() => string[]

clearAssets ​

Removes all of the assets and clears the cache.

ts
toypack.clearAssets();
ts
() => void

getPackageProviders ​

Use this to retrieve all of the registered package providers.

ts
const providers = toypack.getPackageProviders();
ts
/**
 * @returns The package providers.
 */
() => PackageProvider[]

usePackageProvider ​

Adds a package provider.

ts
toypack.usePackageProvider({
   host: "cdn.skypack.dev",
   /* ... */
});
ts
/**
 * @param provider The package provider.
 * @param isMainProvider Set to true to always use this provider first.
 * Defaults to false.
 */
(provider: PackageProvider, isMainProvider?: boolean) => void

installPackage ​

Installs a package from NPM using the registered package providers.

IMPORTANT NOTE

This isn't the same as node where it installs all of the package's dependencies. It simply uses fetch to get the contents of the package from providers such as esm.sh or jsdelivr and adds it to the assets. This means that if you only fetch "bootstrap", deeper imports like "bootstrap/dist/css/bootstrap.min.css" won't be available. To use such subpackages, you'd need to "install" them seperately.

ts
toypack.installPackage("react");
ts
/**
 * @param packagePath The path of the package to install.
 * @param version The version of the package. Defaults to "latest".
 * @returns A Promise that resolves to the installed package.
 */
(packagePath: string, version?: string) =>
   Promise<{
      name: string;
      version: string;
      subpath: string;
      assets: PackageAsset[];
      dtsAssets: PackageAsset[];
   } | null>;

usePlugin ​

Add a plugin.

ts
import samplePlugin from "sample-plugin";

toypack.usePlugin(samplePlugin());
ts
/**
 * @param plugin The plugin to add.
 * @returns The added plugin.
 */
(plugin: Plugin) => Plugin;

removePlugin ​

Removes a plugin. Note that you must pass in the plugin object itself to remove it.

IMPORTANT NOTE

This will not remove the extensions that was added by the plugin.

ts
import samplePlugin from "sample-plugin";

const samplePluginInit = toypack.usePlugin(samplePlugin());
toypack.removePlugin(samplePluginInit);
ts
/**
 * @param plugin The plugin to remove.
 */
(plugin: Plugin) => void

setConfig ​

Use this to change the Toypack config.

ts
toypack.setConfig({
   bundle: {
      mode: "production",
   },
});
ts
/**
 * @param config The Toypack config.
 */
(config: Partial<ToypackConfig>) => void

resetConfig ​

Sets the Toypack's config back to its defaults.

ts
toypack.resetConfig();
ts
() => void

resolve ​

Get the absolute path of the given source path. The source path can be a relative path or a package name.

INFO

This function imitates node's require.resolve algorithm but with a few adjustments.

ts
/**
 * let's say for example these paths exists:
 *
 * /classes/foo.js
 * /node_modules/pkg/index.js
 */

// resolve a relative path
toypack.resolve("../classes/foo"); // null
toypack.resolve("../classes/foo", { baseDir: "src" }); // /classes/foo.js
toypack.resolve("/classes/foo"); // /classes/foo.js

// resolve a package name
toypack.resolve("a"); // null
toypack.resolve("pkg"); // /node_modules/pkg/index.js
ts
/**
 * @param source The source path to resolve.
 * @param options Optional resolve options.
 * @returns The resolved absolute path, or null if it doesn't exist.
 */
(source: string, options?: Partial<ResolveOptions>) => string | null;

setIFrame ​

Adds an IFrame element to use for displaying the bundle's result everytime you run in development mode.

ts
const iframe = document.querySelector("iframe#sandbox")!;
toypack.setIFrame(iframe);
ts
/**
 * @param iframe The iframe element to use.
 */
(iframe: HTMLIFrameElement) => void

unsetIFrame ​

Unsets the IFrame element.

ts
toypack.unsetIFrame();
ts
() => void

clearCache ​

Removes all the cached compilations. Useful when you want to do a hard-run.

INFO

This function always gets called everytime you use the following:

ts
toypack.clearCache();
ts
() => void

getLastBundleResult ​

Use this to retrieve the last bundle result.

ts
toypack.getLastBundleResult();
ts
/**
 * @returns The bundle result object.
 */
() => BundleResult;

Hooks ​

Everything below will show you how to use hooks.

onError ​

Triggered when an error occurs.

ts
toypack.onError((error) => {
   console.log(error.reason);
});
ts
(callback: (error: Error) => void) => void;
ts
interface Error {
   code: number;
   reason: string;
}

onAddOrUpdateAsset ​

Triggered everytime an asset gets added or updated.

ts
toypack.onAddOrUpdateAsset((asset) => {
   console.log(asset);
});
ts
(callback: (asset: Asset) => void) => void;

onRemoveAsset ​

Triggered everytime an asset gets removed.

INFO

Since the moveAsset uses removeAsset under the hood, this will also be triggered when moveAsset is called.

ts
toypack.onRemoveAsset((asset) => {
   console.log(asset);
});
ts
(callback: (asset: Asset) => void) => void;

onInstallPackage ​

Triggered everytime a package gets installed.

ts
toypack.onInstallPackage((packageInfo) => {
   console.log(packageInfo);
});
ts
(callback: (packageInfo: PackageInfo) => void) => void;
ts
interface PackageInfo {
   name: string;
   version: string;
   subpath: string;
   assets: PackageAsset[];
   dtsAssets: PackageAsset[];
}

onResolve ​

Triggered when a module gets resolved.

ts
toypack.onResolve((resolveInfo) => {
   console.log(resolveInfo);
});
ts
(callback: (resolveInfo: ResolveInfo) => void) => void;
ts
interface ResolveInfo {
   rawRequest: string;
   request: string;
   params: Record<string, string | boolean>;
   resolved: string;
   parent: string;
}

onRun ​

Triggered every bundle execution.

ts
toypack.onRun((bundleResult) => {
   console.log(bundleResult);
});
ts
(callback: (bundleResult: BundleResult) => void) => void;