Getting Started
This guide walks you through installing @devhaven/unit-conversion, importing it across different JavaScript runtimes, and configuring your first unit conversions.
Installation
Section titled “Installation”From npm
Section titled “From npm”Install @devhaven/unit-conversion from the npm registry using your preferred package manager:
npm i @devhaven/unit-conversionyarn add @devhaven/unit-conversionpnpm add @devhaven/unit-conversionbun add @devhaven/unit-conversionFrom JSR
Section titled “From JSR”@devhaven/unit-conversion is also published to JSR with native TypeScript support:
deno add jsr:@devhaven/unit-conversionnpx jsr add @devhaven/unit-conversionbunx jsr add @devhaven/unit-conversionpnpm i jsr:@devhaven/unit-conversionyarn add jsr:@devhaven/unit-conversionImporting the Library
Section titled “Importing the Library”The package ships with both ES Modules (ESM) and CommonJS (CJS) builds alongside bundled TypeScript declaration files (.d.ts).
import { Conversion, UNITS, LABELS } from "@devhaven/unit-conversion";const { Conversion, UNITS, LABELS } = require("@devhaven/unit-conversion");import { Conversion, UNITS, LABELS } from "jsr:@devhaven/unit-conversion";Usage Guide
Section titled “Usage Guide”-
Create a
ConversioninstanceInstantiate
Conversionwith default settings (isFloat: true,decimals: 2) or pass a custom configuration object:import { Conversion } from "@devhaven/unit-conversion";// Default configuration: { isFloat: true, decimals: 2, locale: undefined }const convert = new Conversion();// Custom configurationconst preciseConvert = new Conversion({decimals: 4,isFloat: true,locale: "en-US",}); -
Convert values with
.from()and.to()Pass a
numberor numericstringdirectly to theconvertfunction (or callconvert.value(...)), specify the source unit with.from(), and choose the target unit with.to():// Callable syntax (recommended)const length = convert(25).from("kilometer").to("mile");console.log(length);// { value: 15.53, unit: "mi" }// Method syntax (backward-compatible)const temp = convert.value("100").from("celsius").to("kelvin");console.log(temp);// { value: 373.15, unit: "K" } -
Use exported constants & TypeScript types
In addition to
Conversion, you can import unit lists, unit symbol labels, and TypeScript union types for building UIs or validating inputs:import {UNITS,LABELS,getUnitCategory,type AllUnits,type LengthUnits,type ConversionConfig,} from "@devhaven/unit-conversion";// List all supported length unitsconsole.log(UNITS.length);// ["meter", "kilometer", "centimeter", "millimeter", "inch", "foot", "yard", "mile"]// Look up the display symbol for a unitconsole.log(LABELS.kilometer); // "km"console.log(LABELS.celsius); // "°C"// Determine which category a unit belongs toconsole.log(getUnitCategory("pascal")); // "pressure"