Convert
The smallest & fastest library for really easy, totally type-safe unit conversions in TypeScript & JavaScript.
npm install convert
# or
yarn add convert
convert(5, 'miles').to('km');
convertMany('4d16h').to('minutes');
Features
- Full build time and runtime checks of conversions
- Using a web framework like Next.js or Nuxt.js? You get 0-cost build-time conversions. Convert is totally side-effect free, so conversions will be precalculated at build-time, so absolutely zero conversion code is sent to clients!
- Works in browsers and Node.js (UMD, ESModules, and CommonJS builds provided)
- Out of the box ES3 backwards-compatibility (works since Node.js 0.9.1, probably earlier)
- 0 dependencies
- Supports bigints if you pass something with
typeof
bigint
Usage
API documentation for the latest version is generated and available online.
// ESM:
import convert from 'convert';
// CJS:
const {convert} = require('convert');
// 360 seconds into minutes
convert(360, 'seconds').to('minutes');
// -> 6
// BigInt support
convert(20n, 'hours').to('minutes');
// -> 1200n
// We also do length, data, volume, mass, temperature, and more
convert(5, 'kilometers').to('nautical miles');
convert(12, 'pounds').to('ounces');
convert(64, 'bytes').to('KiB');
convert(10, 'atmospheres').to('kPa');
convert(451, 'fahrenheit').to('celsius');
Converting many units
import {convertMany} from 'convert';
const {convertMany} = require('convert');
// Convert 1 day and 8 hours into ms
convertMany('1d8h').to('ms');
Contributing
Below is a list of commands you will probably find useful.
yarn start
Runs the project in development/watch mode. Your project will be rebuilt upon changes. TSDX has a special logger for you convenience. Error messages are pretty printed and formatted for compatibility VS Code’s Problems tab.
Your library will be rebuilt if you make edits.
yarn build
Bundles the package to the dist
folder.
The package is optimized and bundled with Rollup into multiple formats (CommonJS, UMD, and ES Module).
yarn test
Runs the test watcher (Jest) in an interactive mode. By default, runs tests related to files changed since the last commit.
Alternatives
All of them are bad because they aren’t as small and are slower than convert. Benchmarks of popular unit conversion libraries, including convert are available here. Convert is the fastest, taking less than a microsecond for most conversions (that’s a little bit under 2 million per second).
Thanks
Big thanks to @Jdender, @TheAkio, @iCrawl, @p7g, @aequasi, @aetheryx, and the TypeScript Discord server for their help in getting the typesafety working.
Thanks to @MicroDroid for fixing temperature conversion.