Skip to content

format

Formatting utilities, providing date formatting parameters, template variable replacement, plugin template parsing, date formatting, file size formatting, and compression ratio calculation.

Import

typescript
// Submodule import (recommended)
import { getDateFormatParams, parseTemplate, parseTemplateWithDelimiter, parsePluginTemplate, formatDate, formatFileSize, calcRatio } from '@meng-xi/vite-plugin/common/format'
import type { DateFormatOptions } from '@meng-xi/vite-plugin/common/format'

// Barrel import
import { getDateFormatParams, parseTemplate, parseTemplateWithDelimiter, parsePluginTemplate, formatDate, formatFileSize, calcRatio } from '@meng-xi/vite-plugin/common'
import type { DateFormatOptions } from '@meng-xi/vite-plugin/common'

Type Exports

DateFormatOptions

Date formatting parameters interface.

typescript
interface DateFormatOptions {
	[key: string]: string // Supports arbitrary key names for custom placeholders
	YYYY: string // Four-digit year
	YY: string   // Two-digit year
	MM: string   // Two-digit month
	DD: string   // Two-digit day
	HH: string   // Two-digit hour (24-hour format)
	mm: string   // Two-digit minute
	ss: string   // Two-digit second
	SSS: string  // Three-digit millisecond
	timestamp: string // Timestamp in milliseconds
}

getDateFormatParams

Get date formatting parameters object.

typescript
function getDateFormatParams(date?: Date): DateFormatOptions

Parameters

ParameterTypeDefaultDescription
dateDatenew Date()Date object

Returns

DateFormatOptions - Date formatting parameters object

Example

typescript
const params = getDateFormatParams(new Date())
// { YYYY: '2026', MM: '02', DD: '03', HH: '15', mm: '30', ss: '00', ... }

parseTemplate

Replace {{key}} placeholders in a template string.

typescript
function parseTemplate(template: string, values: Record<string, string>): string

Parameters

ParameterTypeDescription
templatestringTemplate string containing {{key}} placeholders
valuesRecord<string, string>Key-value mapping for placeholders, supports merging multiple variable groups (later overrides earlier)

Returns

string - String with placeholders replaced

Notes

  • Regex special characters in key names are automatically escaped
  • $ in values is safely handled to avoid regex replacement issues

Example

typescript
parseTemplate('Hello {{name}}!', { name: 'World' })
// 'Hello World!'

parseTemplate('{{YYYY}}-{{MM}}-{{DD}}', getDateFormatParams())
// '2026-06-06'

parseTemplateWithDelimiter

Replace variable placeholders in a template string with custom delimiters. This is the generic version of parseTemplate.

typescript
function parseTemplateWithDelimiter(
  template: string,
  values: Record<string, string>,
  leftDelimiter?: string,
  rightDelimiter?: string
): string

Parameters

ParameterTypeDefaultDescription
templatestring-Template string with placeholders
valuesRecord<string, string>-Key-value mapping for placeholders
leftDelimiterstring'{{'Left delimiter
rightDelimiterstring'}}'Right delimiter

Returns

string - String with placeholders replaced

Notes

  • Generic template parsing function supporting custom delimiters
  • Regex special characters in key names are automatically escaped
  • $ in values is safely handled to avoid regex replacement issues

Example

typescript
parseTemplateWithDelimiter('Hello {{name}}!', { name: 'World' })
// 'Hello World!'

parseTemplateWithDelimiter('Hello {name}!', { name: 'World' }, '{', '}')
// 'Hello World!'

// formatDate internally uses this function with { and } delimiters
parseTemplateWithDelimiter('{YYYY}-{MM}-{DD}', getDateFormatParams(), '{', '}')
// '2026-06-06'

formatDate

Format a date string using {key} single-brace placeholders.

typescript
function formatDate(date: Date, format: string): string

Parameters

ParameterTypeDescription
dateDateDate object
formatstringFormat string, supports {YYYY}, {MM}, {DD}, {HH}, {mm}, {ss} and other placeholders

Returns

string - Formatted date string

Example

typescript
formatDate(new Date(), '{YYYY}-{MM}-{DD}T{HH}:{mm}:{ss}')
// '2026-06-06T15:30:00'

formatDate(new Date(), '{YYYY}.{MM}.{DD}')
// '2026.06.06'

parsePluginTemplate

Parse plugin file header templates, supporting date, custom field, plugin name, and version placeholders. Primarily used by generateRouter's headerTemplate option.

typescript
function parsePluginTemplate(
  template: string,
  params: {
    name?: string
    version?: string
    customFields?: Record<string, string>
    defaultDateFormat?: string
  }
): string

Parameters

ParameterTypeDescription
templatestringTemplate string
paramsobjectParsing parameters
params.namestringPlugin name, replaces {name}
params.versionstringPlugin version, replaces {version}
params.customFieldsRecord<string, string>Custom field key-value pairs, replaces {custom:KEY}
params.defaultDateFormatstringDefault date format, defaults to YYYY-MM-DD HH:mm:ss

Returns

string - Parsed string

Supported Placeholders

PlaceholderDescriptionExample
{date}Default format datetime2026-06-25 14:30:00
{date:FORMAT}Custom format date (FORMAT uses bare tokens, e.g., YYYY-MM-DD){date:YYYY/MM/DD}2026/06/25
{custom:KEY}Custom field, preserves original placeholder if not provided{custom:author}MengXi Studio
{name}Plugin namegenerate-router
{version}Plugin version0.2.7

Date Format Note

The FORMAT in {date:FORMAT} uses bare tokens (e.g., YYYY-MM-DD). The function internally wraps them into braces before calling formatDate, so there's no need to manually write {YYYY}-{MM}-{DD}.

Example

typescript
parsePluginTemplate('{name} v{version} ({date:YYYY-MM-DD})', {
  name: 'generate-router',
  version: '0.2.7',
  customFields: { author: 'MengXi Studio' }
})
// 'generate-router v0.2.7 (2026-06-25)'

parsePluginTemplate('{custom:author} - {date}', {
  customFields: { author: 'MengXi Studio' }
})
// 'MengXi Studio - 2026-06-25 14:30:00'

// Keys not provided in customFields preserve the original placeholder
parsePluginTemplate('{custom:author}', {})
// '{custom:author}'

formatFileSize

Format bytes into a human-readable file size string.

typescript
function formatFileSize(bytes: number): string

Parameters

ParameterTypeDescription
bytesnumberFile size in bytes

Returns

string - Formatted file size string

Conversion Rules

RangeFormatExample
Less than 1KBxB512B
Less than 1MBx.xKB1.5KB
Greater than 1MBx.xxMB2.35MB

Example

typescript
formatFileSize(512) // '512B'
formatFileSize(1536) // '1.5KB'
formatFileSize(2461726) // '2.35MB'

calcRatio

Calculate compression ratio percentage.

typescript
function calcRatio(originalSize: number, compressedSize: number): number

Parameters

ParameterTypeDescription
originalSizenumberOriginal size (bytes)
compressedSizenumberCompressed size (bytes)

Returns

number - Compression ratio percentage (0-100), e.g., 65.2 means 65.2% size reduction

Notes

  • Formula: (1 - compressedSize / originalSize) * 100, rounded to one decimal place
  • Returns 0 when originalSize is 0, avoiding division by zero

Example

typescript
calcRatio(10000, 6000)  // 40.0
calcRatio(10000, 10000) // 0
calcRatio(0, 0)         // 0

Released under the MIT License.