Creating Typescript Library using Webpack

4 minute read

In this article we will see how can you create your own typescript library that you can easily consume in your another typescript project. Also we will see how we can create type definition bundle file for our own library. Finally we will see which folder is required to publish to npm portal to have our own little library published and available for our friends.

Introduction

In you enterprise if you want to create shared JavaScript library then webpack and typescript comes first in mind. However, there is no sample project or example exist in google that demonstrates how to achieve it. In this sample project I tried to demonstrate how can you create a library project using typescript and webpack and then create your own npm packages both for JavaScript bundle and @types bundle. Also you will see how can you use them in your sample project. I hope you will enjoy this project and learn something! docs

 

What are we going to solve ?

This project is demonstrating how to create your own library using typescript and webpack. Then consume that library in another webpack project.

  • create a library from typescript
  • create a bundle (.js) for JavaScript
  • create a bundle (.d.ts) for definition files for typescript
  • consume library in client project by npm link script.

We have created 2 projects one is lib-pj which is library project and the other is client-pj which is client project that is going to consume lib-pj

We are using

  • webpack for building, bundling etc.
  • ts-loader for compiling typescript and
  • declaration-bundler-webpack-plugin for bundling type definition files

Getting Tool Sets Ready

Grunge hipster wooden desktop with computer, digital tablet

We are using:

  • Webpack and
  • Typescript

of-course, I am using my favorite  VSCode editor , you can use yours favorite.

Solution

Create 2 projects at your root folder client-pj and lib-pj. Client Project is where we will consume the output from Library project.

Creating Library Project

Library Books

Lets work on library project where you want to create your sharable code. We have added our model classes and services in this folder and now In order to compile typescript code you need tsconfig.json . please copy below code and put in tsconfig.json inside lib-pj

https://gist.github.com/rupeshtiwari/39a4c9adb875169e1210eff6390e63ed

Lets create webpack.config.js file inside library project make sure you have ts-loader installed which is used to load typescript and compile them in JavaScript

Here is the final webpack.config.js file

https://gist.github.com/rupeshtiwari/38498c95aa0d612bdafbc93500da4da1

Above setup will be enough to create our index.js file. However, the major challenge is to how to create the typedefinition bundle file for our library. For that I have used declaration-bundler-webpack-plugin  and with this plugin it was very easy to generate my own index.d.ts file. Have a look in below code how to use DeclarationBundlerPlugin plugin to get your index.d.ts file created. This is magic. I loved the DeclarationBundlerPlugin webpack plugin!

plugins: [
    
    new DeclarationBundlerPlugin({
      moduleName: '"@mycomp/mylib"',
      out: '../@types/index.d.ts',
    }),
     
  ],
};

Creating Client Project

Now in client project we can easily consume index.js Create new webpack.config for your client-pj by pasting below code. Client project will refer to the Library project by leveraging tsconfig path feature. You need not build library project and consume in client project for local development because it will slow down your development speed. Therefore, the best practice is refer your client project via path feature of tsconfig.json. The same path configuration can be also put in webpack resolve property such that it compiles the typescript files from library project

// tsconfig.json
...{
    path : {
        "@lib" : ["./lib-pj/src/index.ts"]
    }
    ... 
}

// webpack.config.js ... { resolve :{ "@lib" :
path.resolve("./lib-pj/src/index.ts") } }

Here is my final webpack.config.json file code:

const webpack = require('webpack');
const path = require('path');
const ROOT = __dirname;
const DESTINATION = path.join(ROOT, '/dist');
/** wepback resolve */
const RESOLVE = {
  extensions: ['.tsx', '.ts', '.js', '.html'],
};

/\*_ webpack plugins _/ const PLUGINS = []; const MODULE = { rules: [ // Scripts
{ test: /\.ts$/, exclude: [/node_modules/], loader: 'ts-loader', include:
[ROOT], }, ], }; const OUTPUT = { filename: 'index.js', libraryTarget: 'umd',
library: 'myclient', path: DESTINATION, };

module.exports = { node: { fs: 'empty', }, entry: { app: ROOT + '/src/index.ts',
}, context: ROOT, resolve: RESOLVE, mode: 'development', module: MODULE,
plugins: PLUGINS, devtool: 'source-map', devServer: {}, output: OUTPUT, };

Then you are all set!

Running  the Build

Now it's time to build our library project and share it. We will first build lib-pj so that we can create output from this project and share it to npm portal.

 # go to lib-pj and run below scripts # 
npm run build

After running above build script in lib-pj you will see below 2 folders:

  • dist Folder
    • index.js
    • index.js.map
    • package.json
  • @types Folder
    • index.d.ts
    • package.json
# go to client-pj and run below scripts #
npm run build

Publishing to NPM

Now build client-pj by running build script, which will link to above 2 npm packages. You can now safely publish this dist folder in to npm library by running npm publish command and have fun :)

some times you want to publish your type definition files in a separate npm package that also you can do by publishing @types folder separately to npm.

Getting this Source Code

# in your machine open command prompt and run below script #
git clone https://github.com/roopkt/webpack-typesript-library-consumption-sample.git

Installing node packages

windows installation workers

We want to install npm packages to both client-pj and lib-pj project. Please follow below instruction:

# run below scripts from lib-pj folder #
npm i

# run below scripts from client-pj folder

npm i 

Should you have Questions

If you have any questions or issues or suggestions please feel free to communicate me or create issue in this git repository.

Releases

I have created few releases in my Github repository See all of the releases here.

message from rupesh tiwari

https://www.youtube.com/watch?v=gzqDoHYO_xk

Enroll to full stack master

❤️ Hey Viewers! show your support & subscribe to full stack master school to watch full stack JavaScript HD course videos including node.js, angular, express, webpack and much more. Download source code, slides and step by step guide. Learn more at https://blog.rupeshtiwari.com/subscribe 💥 I am super excited to teach you at Full Stack Master!