Build utilities for Vercel platform builders and serverless functions, providing utilities for creating and managing Lambda functions, file operations, and build-time helpers for the Vercel deployment platform
npx @tessl/cli install tessl/npm-vercel--build-utils@2.7.0@vercel/build-utils is a comprehensive TypeScript library providing essential build utilities for the Vercel platform. It serves as the foundation for creating custom builders and managing serverless functions, offering file system operations, Lambda function creation and management, process execution utilities, and framework detection capabilities.
npm install @vercel/build-utilsimport {
FileBlob,
FileFsRef,
FileRef,
Lambda,
createLambda,
Prerender,
download,
glob,
getWriteableDirectory,
rename,
streamToBuffer,
readConfigFile,
spawnAsync,
execAsync,
spawnCommand,
execCommand,
installDependencies,
runNpmInstall,
runPackageJsonScript,
walkParentDirs,
getNodeVersion,
getNodeBinPath,
detectBuilders,
detectOutputDirectory,
detectApiDirectory,
detectFramework,
DetectorFilesystem,
isOfficialRuntime,
isStaticRuntime,
getPlatformEnv,
shouldServe,
debug,
NowBuildError
} from "@vercel/build-utils";For CommonJS:
const {
FileBlob,
FileFsRef,
FileRef,
Lambda,
createLambda,
Prerender,
download,
glob,
getWriteableDirectory,
rename,
streamToBuffer,
readConfigFile,
spawnAsync,
execAsync,
spawnCommand,
execCommand,
installDependencies,
runNpmInstall,
runPackageJsonScript,
walkParentDirs,
getNodeVersion,
getNodeBinPath,
detectBuilders,
detectOutputDirectory,
detectApiDirectory,
detectFramework,
DetectorFilesystem,
isOfficialRuntime,
isStaticRuntime,
getPlatformEnv,
shouldServe,
debug,
NowBuildError
} = require("@vercel/build-utils");import {
FileBlob,
FileFsRef,
createLambda,
download,
glob,
spawnAsync,
detectBuilders,
getPlatformEnv,
NowBuildError
} from "@vercel/build-utils";
// Create file references
const fileBlob = new FileBlob({ data: "console.log('Hello World')" });
const fileFsRef = await FileFsRef.fromFsPath({ fsPath: "/path/to/file.js" });
// Create a Lambda function
const files = { "index.js": fileBlob };
const lambda = await createLambda({
files,
handler: "index.handler",
runtime: "nodejs18.x",
environment: { NODE_ENV: "production" }
});
// Download files to filesystem
const downloadedFiles = await download(files, "/tmp/build", { isDev: false });
// Find files with patterns
const sourceFiles = await glob("**/*.js", "/src");
// Execute shell commands
await spawnAsync("npm", ["install"], { cwd: "/project" });
// Detect appropriate builders
const fileList = ["package.json", "pages/index.js", "api/users.js"];
const result = await detectBuilders(fileList);
// Handle environment variables
const deploymentUrl = getPlatformEnv("URL");
const region = getPlatformEnv("REGION");
// Error handling
try {
await spawnAsync("npm", ["run", "build"]);
} catch (error) {
if (error instanceof NowBuildError) {
console.error(`Build failed [${error.code}]: ${error.message}`);
}
}@vercel/build-utils is organized around several key components:
FileBlob, FileFsRef, FileRef) for representing different file sourcesFile handling, downloading, and pattern matching utilities for managing build assets and source files.
function download(files: Files, basePath: string, meta?: Meta): Promise<DownloadedFiles>;
function glob(pattern: string, opts: GlobOptions | string, mountpoint?: string): Promise<FsFiles>;Creation and management of serverless Lambda functions with ZIP packaging and configuration options.
function createLambda(options: CreateLambdaOptions): Promise<Lambda>;
interface CreateLambdaOptions {
files: Files;
handler: string;
runtime: string;
memory?: number;
maxDuration?: number;
environment?: Environment;
}
class Lambda {
type: 'Lambda';
zipBuffer: Buffer;
handler: string;
runtime: string;
memory?: number;
maxDuration?: number;
environment: Environment;
}Utilities for executing shell commands, installing dependencies, and running user scripts safely.
function spawnAsync(command: string, args: string[], opts?: SpawnOptionsExtended): Promise<void>;
function execAsync(command: string, args: string[], opts?: SpawnOptionsExtended): Promise<{ stdout: string; stderr: string; code: number }>;Automatic detection of project frameworks and configuration of appropriate build strategies.
function detectBuilders(files: string[], pkg?: PackageJson, options?: Options): Promise<{
builders: Builder[] | null;
errors: ErrorResponse[] | null;
warnings: ErrorResponse[];
defaultRoutes: Route[] | null;
redirectRoutes: Route[] | null;
rewriteRoutes: Route[] | null;
errorRoutes: Route[] | null;
}>;Helper functions for Vercel platform integration, environment variable handling, and runtime detection.
function isOfficialRuntime(desired: string, name?: string): boolean;
function getPlatformEnv(name: string): string | undefined;interface Files {
[filePath: string]: File;
}
interface File {
type: string;
mode: number;
contentType?: string;
toStream: () => NodeJS.ReadableStream;
fsPath?: string;
}
interface Config {
[key: string]: string | string[] | boolean | number | { [key: string]: string } | BuilderFunctions | undefined;
maxLambdaSize?: string;
includeFiles?: string | string[];
excludeFiles?: string | string[];
bundle?: boolean;
functions?: BuilderFunctions;
outputDirectory?: string;
installCommand?: string;
buildCommand?: string;
devCommand?: string;
framework?: string;
nodeVersion?: string;
}
interface Meta {
isDev?: boolean;
devCacheDir?: string;
skipDownload?: boolean;
requestPath?: string | null;
filesChanged?: string[];
filesRemoved?: string[];
env?: Env;
buildEnv?: Env;
}
interface Env {
[name: string]: string | undefined;
}
interface Environment {
[key: string]: string;
}
interface BuildOptions {
files: Files;
entrypoint: string;
workPath: string;
repoRootPath?: string;
config: Config;
meta?: Meta;
}
interface AnalyzeOptions {
files: {
[filePath: string]: FileRef;
};
entrypoint: string;
workPath: string;
config: Config;
}
interface PrepareCacheOptions {
files: Files;
entrypoint: string;
workPath: string;
cachePath: string;
config: Config;
}
interface Builder {
use: string;
src?: string;
config?: Config;
}
interface BuilderFunctions {
[key: string]: {
memory?: number;
maxDuration?: number;
runtime?: string;
includeFiles?: string;
excludeFiles?: string;
};
}
interface NodeVersion {
major: number;
range: string;
runtime: string;
discontinueDate?: Date;
}
namespace PackageJson {
export interface Author {
name: string;
email?: string;
homepage?: string;
}
export interface BinMap {
[commandName: string]: string;
}
export interface Repository {
type: string;
url: string;
}
export interface DependencyMap {
[dependencyName: string]: string;
}
export interface ScriptsMap {
[scriptName: string]: string;
}
export interface Engines {
node?: string;
npm?: string;
}
}
interface PackageJson {
readonly name?: string;
readonly version?: string;
readonly description?: string;
readonly keywords?: string[];
readonly homepage?: string;
readonly license?: string;
readonly author?: string | PackageJson.Author;
readonly main?: string;
readonly bin?: string | PackageJson.BinMap;
readonly repository?: string | PackageJson.Repository;
readonly scripts?: PackageJson.ScriptsMap;
readonly dependencies?: PackageJson.DependencyMap;
readonly devDependencies?: PackageJson.DependencyMap;
readonly peerDependencies?: PackageJson.DependencyMap;
readonly engines?: PackageJson.Engines;
readonly private?: boolean;
}