CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-snowpack

A lightning-fast frontend build tool designed to leverage JavaScript's native ESM system for unbundled development with instant browser updates.

82

1.22x
Overview
Eval results
Files

utilities.mddocs/

Utility Functions

Snowpack provides various utility functions for file management, URL resolution, package handling, path manipulation, and build system integration. These utilities support both internal operations and external plugin development.

Capabilities

File URL Resolution

Get URLs for files and packages within the Snowpack build system.

/**
 * Get URL for a file location
 * @param fileLoc - File location path
 * @param config - Snowpack configuration
 * @returns File URL or null if not found
 */
function getUrlForFile(fileLoc: string, config: SnowpackConfig): string | null;
import { getUrlForFile, loadConfiguration } from "snowpack";

const config = await loadConfiguration();

// Get URL for source file
const url = getUrlForFile('/src/components/Button.jsx', config);
// Result: "/src/components/Button.js"

// Get URL for static asset
const assetUrl = getUrlForFile('/public/logo.png', config);
// Result: "/logo.png"

Package Preparation

Prepare packages for the build process by installing and processing dependencies.

/**
 * Prepare packages for the build process
 * @param options - Command options with configuration
 * @returns Promise resolving when packages are prepared
 */
function preparePackages({config}: CommandOptions): Promise<void>;
import { preparePackages, loadConfiguration } from "snowpack";

const config = await loadConfiguration();

// Prepare all packages
await preparePackages({ config });

// Packages are now ready for development or building
console.log('Packages prepared successfully');

Cache Management

Clear the Snowpack cache directory to resolve build issues.

/**
 * Clear the Snowpack cache directory
 * @returns Promise resolving when cache is cleared
 */
function clearCache(): Promise<void>;
import { clearCache } from "snowpack";

// Clear cache before build (useful for troubleshooting)
console.log('Clearing cache...');
await clearCache();
console.log('Cache cleared successfully');

Lockfile Management

Read and manage the Snowpack dependency lockfile.

/**
 * Read the snowpack.deps.json lockfile
 * @param cwd - Current working directory
 * @returns Promise resolving to lockfile manifest or null if not found
 */
function loadLockfile(cwd: string): Promise<LockfileManifest | null>;

/**
 * Lockfile manifest structure
 */
interface LockfileManifest {
  /** Package dependencies with versions */
  dependencies: {[packageName: string]: string};
  /** Import specifier to resolved URL mapping */
  lock: {[specifier: string]: string};
}
import { loadLockfile } from "snowpack";

// Load lockfile from current directory
const lockfile = await loadLockfile(process.cwd());

if (lockfile) {
  console.log('Dependencies:', lockfile.dependencies);
  console.log('Import map:', lockfile.lock);
} else {
  console.log('No lockfile found');
}

Path and URL Utilities

Extension Manipulation

Work with file extensions for build processing.

/**
 * Get file extension from path
 * @param str - File path or name
 * @returns File extension including dot
 */
function getExtension(str: string): string;

/**
 * Check if string has specific extension
 * @param str - File path or name
 * @param ext - Extension to check (with or without dot)
 * @returns True if file has the extension
 */
function hasExtension(str: string, ext: string): boolean;

/**
 * Replace file extension
 * @param fileName - Original file name
 * @param oldExt - Current extension
 * @param newExt - New extension
 * @returns File name with new extension
 */
function replaceExtension(fileName: string, oldExt: string, newExt: string): string;

/**
 * Add extension to file name
 * @param fileName - File name without extension
 * @param newExt - Extension to add
 * @returns File name with extension
 */
function addExtension(fileName: string, newExt: string): string;

/**
 * Remove extension from file name
 * @param fileName - File name with extension
 * @param oldExt - Extension to remove
 * @returns File name without extension
 */
function removeExtension(fileName: string, oldExt: string): string;
import { 
  getExtension, 
  hasExtension, 
  replaceExtension, 
  addExtension, 
  removeExtension 
} from "snowpack";

// Extension utilities
const ext = getExtension('app.tsx');        // '.tsx'
const hasTs = hasExtension('app.tsx', 'tsx'); // true
const renamed = replaceExtension('app.tsx', '.tsx', '.js'); // 'app.js'
const withExt = addExtension('app', '.js');  // 'app.js'
const noExt = removeExtension('app.js', '.js'); // 'app'

Path Manipulation

Manipulate URL and file paths for build processing.

/**
 * Add leading slash to path
 * @param path - Path string
 * @returns Path with leading slash
 */
function addLeadingSlash(path: string): string;

/**
 * Add trailing slash to path
 * @param path - Path string
 * @returns Path with trailing slash
 */
function addTrailingSlash(path: string): string;

/**
 * Remove leading slash from path
 * @param path - Path string
 * @returns Path without leading slash
 */
function removeLeadingSlash(path: string): string;

/**
 * Remove trailing slash from path
 * @param path - Path string
 * @returns Path without trailing slash
 */
function removeTrailingSlash(path: string): string;

/**
 * Calculate relative URL between two paths
 * @param path1 - From path
 * @param path2 - To path
 * @returns Relative URL
 */
function relativeURL(path1: string, path2: string): string;
import { 
  addLeadingSlash, 
  addTrailingSlash, 
  removeLeadingSlash, 
  removeTrailingSlash,
  relativeURL 
} from "snowpack";

// Path manipulation
const withLeading = addLeadingSlash('src/app.js');    // '/src/app.js'
const withTrailing = addTrailingSlash('/src');        // '/src/'
const noLeading = removeLeadingSlash('/src/app.js');  // 'src/app.js'
const noTrailing = removeTrailingSlash('/src/');      // '/src'
const relative = relativeURL('/src/components/', '/src/utils/'); // '../utils/'

Import and Package Utilities

Import Specifier Analysis

Analyze and manipulate package import specifiers.

/**
 * Parse package import specifier into name and subpath
 * @param imp - Import specifier (e.g., "react/jsx-runtime")
 * @returns Tuple of [packageName, subpath]
 */
function parsePackageImportSpecifier(imp: string): [string, string | null];

/**
 * Check if specifier is a path import (local file)
 * @param spec - Import specifier
 * @returns True if specifier is a path import
 */
function isPathImport(spec: string): boolean;

/**
 * Check if value is a remote URL
 * @param val - Value to check
 * @returns True if value is a remote URL
 */
function isRemoteUrl(val: string): boolean;

/**
 * Check if import URL is from a specific package
 * @param importUrl - Import URL
 * @param packageName - Package name to check
 * @returns True if import is from the package
 */
function isImportOfPackage(importUrl: string, packageName: string): boolean;
import { 
  parsePackageImportSpecifier, 
  isPathImport, 
  isRemoteUrl, 
  isImportOfPackage 
} from "snowpack";

// Import analysis
const [pkg, subpath] = parsePackageImportSpecifier('react/jsx-runtime');
// pkg: 'react', subpath: 'jsx-runtime'

const isLocal = isPathImport('./components/Button'); // true
const isPath = isPathImport('react'); // false

const isUrl = isRemoteUrl('https://cdn.skypack.dev/react'); // true
const isFile = isRemoteUrl('./app.js'); // false

const isReact = isImportOfPackage('/web_modules/react.js', 'react'); // true

Dependency Resolution

Resolve package dependencies and manifests.

/**
 * Resolve dependency manifest from node_modules
 * @param dep - Dependency name
 * @param cwd - Current working directory
 * @returns Tuple of [manifestPath, manifestContent] or [null, null]
 */
function resolveDependencyManifest(dep: string, cwd: string): [string | null, any | null];

/**
 * Create install target from package specifier
 * @param specifier - Package specifier
 * @param all - Include all exports (default true)
 * @returns Install target object
 */
function createInstallTarget(specifier: string, all?: boolean): InstallTarget;

/**
 * Install target interface
 */
interface InstallTarget {
  /** Package specifier */
  specifier: string;
  /** Include all exports */
  all: boolean;
  /** Default export */
  default?: boolean;
  /** Named exports */
  namespace?: boolean;
}
import { resolveDependencyManifest, createInstallTarget } from "snowpack";

// Resolve package manifest
const [manifestPath, manifest] = resolveDependencyManifest('react', process.cwd());
if (manifest) {
  console.log('React version:', manifest.version);
  console.log('Main entry:', manifest.main);
}

// Create install target
const target = createInstallTarget('react', true);
// { specifier: 'react', all: true }

File System Utilities

File Operations

Read files with automatic encoding detection and type handling.

/**
 * Read file with automatic encoding detection
 * @param filepath - Path to file
 * @returns Promise resolving to file contents as string or Buffer
 */
function readFile(filepath: string): Promise<string | Buffer>;

/**
 * Check if file system events are enabled
 * @returns True if fsevents is available (macOS)
 */
function isFsEventsEnabled(): boolean;

/**
 * Safely delete files from build directory
 * @param dir - Directory to clean
 * @param config - Snowpack configuration
 */
function deleteFromBuildSafe(dir: string, config: SnowpackConfig): void;
import { readFile, isFsEventsEnabled, deleteFromBuildSafe } from "snowpack";

// Read file with automatic encoding
const content = await readFile('./src/app.js');
if (typeof content === 'string') {
  console.log('Text file:', content.length, 'characters');
} else {
  console.log('Binary file:', content.length, 'bytes');
}

// Check file watching capabilities
if (isFsEventsEnabled()) {
  console.log('Fast file watching available (macOS)');
}

// Clean build directory
deleteFromBuildSafe('./dist', config);

Source Map Utilities

Add source map URLs to compiled code.

/**
 * Add CSS source mapping URL
 * @param code - CSS code
 * @param sourceMappingURL - Source map URL
 * @returns CSS with source map comment
 */
function cssSourceMappingURL(code: string, sourceMappingURL: string): string;

/**
 * Add JavaScript source mapping URL
 * @param code - JavaScript code
 * @param sourceMappingURL - Source map URL
 * @returns JavaScript with source map comment
 */
function jsSourceMappingURL(code: string, sourceMappingURL: string): string;
import { cssSourceMappingURL, jsSourceMappingURL } from "snowpack";

// Add source maps to compiled code
const cssWithMap = cssSourceMappingURL(
  '.button { color: blue; }',
  './app.css.map'
);
// Result: '.button { color: blue; }\n/*# sourceMappingURL=./app.css.map */'

const jsWithMap = jsSourceMappingURL(
  'export const app = "hello";',
  './app.js.map'
);
// Result: 'export const app = "hello";\n//# sourceMappingURL=./app.js.map'

HTML Manipulation

Modify HTML content during build processing.

/**
 * Append HTML content to document head
 * @param doc - HTML document string
 * @param htmlToAdd - HTML to append to head
 * @returns Modified HTML document
 */
function appendHtmlToHead(doc: string, htmlToAdd: string): string;

/**
 * Check if pathname represents JavaScript
 * @param pathname - File pathname
 * @returns True if pathname is JavaScript
 */
function isJavaScript(pathname: string): boolean;
import { appendHtmlToHead, isJavaScript } from "snowpack";

// Add content to HTML head
const originalHtml = '<html><head><title>App</title></head><body></body></html>';
const modifiedHtml = appendHtmlToHead(originalHtml, '<meta charset="utf-8">');

// Check file type
const isJs = isJavaScript('/src/app.js');     // true
const isTs = isJavaScript('/src/app.ts');     // false
const isJsx = isJavaScript('/src/App.jsx');   // true

Constants and Patterns

Regular Expressions

/**
 * Regex for detecting dotfiles
 */
const IS_DOTFILE_REGEX: RegExp;

/**
 * HTML script tag regex
 */
const HTML_JS_REGEX: RegExp;

/**
 * HTML style tag regex
 */
const HTML_STYLE_REGEX: RegExp;

/**
 * CSS import regex
 */
const CSS_REGEX: RegExp;

/**
 * Svelte/Vue script tag regex
 */
const SVELTE_VUE_REGEX: RegExp;

/**
 * Astro frontmatter regex
 */
const ASTRO_REGEX: RegExp;

Cache and File Names

/**
 * Default lockfile name
 */
const LOCKFILE_NAME: string; // 'snowpack.deps.json'

/**
 * Build cache directory
 */
const BUILD_CACHE: string;

/**
 * Global cache directory
 */
const GLOBAL_CACHE_DIR: string;

Hot Module Replacement

/**
 * HMR client code for injection
 */
const HMR_CLIENT_CODE: string;

/**
 * HMR error overlay code
 */
const HMR_OVERLAY_CODE: string;

Type Utilities

/**
 * Utility type for awaited promises
 */
type Awaited<T> = T extends PromiseLike<infer U> ? Awaited<U> : T;

/**
 * Type guard for truthy values
 * @param item - Item to check
 * @returns True if item is truthy
 */
function isTruthy<T>(item: T | false | null | undefined): item is T;
import { isTruthy } from "snowpack";

// Filter truthy values
const values = ['hello', '', null, 'world', undefined, 0];
const truthyValues = values.filter(isTruthy);
// Result: ['hello', 'world']

Install with Tessl CLI

npx tessl i tessl/npm-snowpack

docs

build-system.md

cli.md

configuration.md

development-server.md

index.md

plugins.md

utilities.md

tile.json