API Examples
This page demonstrates how to use Toypack.
run
Starts the bundling process.
const bundleResult = await toypack.run();
/**
* @returns A Promise that resolves to the bundle result object.
*/
() => Promise<BundleResult>;
addOrUpdateAsset
Adds or updates an asset.
- See Asset Interface
toypack.addOrUpdateAsset("/index.js", "console.log(123);");
/**
* @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.
- See Asset Interface
const asset = toypack.getAsset("/index.js");
/**
* @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.
toypack.removeAsset("/index.js");
/**
* @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.
toypack.removeDirectory("/src");
/**
* @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.
toypack.moveAsset("/index.js", "/src/index.js");
/**
* @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.
toypack.moveDirectory("/src", "/");
/**
* @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.
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)!;
}
/**
* @returns An array containing the sources of the existing assets.
*/
() => string[]
clearAssets
Removes all of the assets and clears the cache.
toypack.clearAssets();
() => void
getPackageProviders
Use this to retrieve all of the registered package providers.
const providers = toypack.getPackageProviders();
/**
* @returns The package providers.
*/
() => PackageProvider[]
usePackageProvider
Adds a package provider.
toypack.usePackageProvider({
host: "cdn.skypack.dev",
/* ... */
});
/**
* @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.
toypack.installPackage("react");
/**
* @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.
import samplePlugin from "sample-plugin";
toypack.usePlugin(samplePlugin());
/**
* @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.
import samplePlugin from "sample-plugin";
const samplePluginInit = toypack.usePlugin(samplePlugin());
toypack.removePlugin(samplePluginInit);
/**
* @param plugin The plugin to remove.
*/
(plugin: Plugin) => void
setConfig
Use this to change the Toypack config.
toypack.setConfig({
bundle: {
mode: "production",
},
});
/**
* @param config The Toypack config.
*/
(config: Partial<ToypackConfig>) => void
resetConfig
Sets the Toypack's config back to its defaults.
toypack.resetConfig();
() => 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.
/**
* 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
/**
* @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.
const iframe = document.querySelector("iframe#sandbox")!;
toypack.setIFrame(iframe);
/**
* @param iframe The iframe element to use.
*/
(iframe: HTMLIFrameElement) => void
unsetIFrame
Unsets the IFrame element.
toypack.unsetIFrame();
() => 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:
- clearAssets
- usePlugin
- removePlugin
- setConfig (only when something important has changed)
toypack.clearCache();
() => void
getLastBundleResult
Use this to retrieve the last bundle result.
toypack.getLastBundleResult();
/**
* @returns The bundle result object.
*/
() => BundleResult;
Hooks
Everything below will show you how to use hooks.
onError
Triggered when an error occurs.
toypack.onError((error) => {
console.log(error.reason);
});
(callback: (error: Error) => void) => void;
interface Error {
code: number;
reason: string;
}
onAddOrUpdateAsset
Triggered everytime an asset gets added or updated.
- See Asset Interface
toypack.onAddOrUpdateAsset((asset) => {
console.log(asset);
});
(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.
- See Asset Interface
toypack.onRemoveAsset((asset) => {
console.log(asset);
});
(callback: (asset: Asset) => void) => void;
onInstallPackage
Triggered everytime a package gets installed.
toypack.onInstallPackage((packageInfo) => {
console.log(packageInfo);
});
(callback: (packageInfo: PackageInfo) => void) => void;
interface PackageInfo {
name: string;
version: string;
subpath: string;
assets: PackageAsset[];
dtsAssets: PackageAsset[];
}
onResolve
Triggered when a module gets resolved.
toypack.onResolve((resolveInfo) => {
console.log(resolveInfo);
});
(callback: (resolveInfo: ResolveInfo) => void) => void;
interface ResolveInfo {
rawRequest: string;
request: string;
params: Record<string, string | boolean>;
resolved: string;
parent: string;
}
onRun
Triggered every bundle execution.
toypack.onRun((bundleResult) => {
console.log(bundleResult);
});
(callback: (bundleResult: BundleResult) => void) => void;