Sometimes You Just Need A Dumb Library

How to create a library with Rollup and Typescript

Photo by Benjamin Davies on Unsplash

Our Goal: A Utility To Get Valid Date Objects

export function toDateObject(myDate: any): Date | undefined {
if (!myDate || myDate === undefined) {
return undefined;
}

if (myDate instanceof String || typeof myDate === 'string') {
return new Date(`${myDate}`);
}

if (typeof myDate === 'number' && !isNaN(myDate)) {
return new Date(myDate);
}

// It case Firebase Timestamp format too
if (myDate && myDate.seconds >= 0 && myDate.nanoseconds >= 0) {
return new Date(myDate.toDate());
}

return myDate;
}

Create A Library

mkdir utils && cd utils
{
"name": "utils",
"version": "1.0.0",
"devDependencies": {
"@types/node": "^13.9.1",
"rimraf": "^3.0.2",
"rollup": "^2.1.0",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-typescript": "^1.0.1",
"tslib": "^1.11.1",
"typescript": "^3.8.3"
},
"main": "lib/index.cjs.js",
"module": "lib/index.js",
"types": "lib/index.d.ts",
"scripts": {
"prepare": "npm run build",
"build": "rimraf lib && rollup -c && tsc"
},
"files": [
"lib",
"README.md"
]
}

Typescript

{
"compilerOptions": {
"target": "ES2017",
"module": "esnext",
"declaration": true,
"outDir": "lib",
"strict": true,
"removeComments": true
},
"include": [
"src/**/*"
],
"exclude": ["node_modules"]
}

Rollup

// https://github.com/rollup/rollup-starter-lib
// https://buzut.net/configurer-rollup-bundles-esm-cjs/
// https://dev.to/proticm/how-to-setup-rollup-config-45mk

import typescript from 'rollup-plugin-typescript';
import commonjs from 'rollup-plugin-commonjs';

import pkg from './package.json';

export default {
input: './src/index.ts',
plugins: [
commonjs(),
typescript()
],
output: {
format: 'cjs',
file: pkg.main
}
}

Installation Of The Dependencies

mkdir src && touch src/index.ts
npm install

Coding

npm run build

Summary

Freelancer by day | Creator of DeckDeckGo by night | Organizer of the Ionic and IndieHackers Zürich Meetup

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store