Building Modules and Module Typing

Learn how to build a self-contained module using webpack, resolve dependency errors, generate a declaration file, and package your TypeScript library for use with npm.

We'll cover the following

Building a module

Our MicroEventBus class has a single dependency, which is the RxJS library. If we were to include the JavaScript file that we have generated, that is, MicroEventBus.js, directly into an HTML page and attempt to run it, we would find two errors logged to the console. These are:

Uncaught ReferenceError: exports is not defined
Uncaught TypeError: Cannot read property 'on' of undefined

These errors are indicating that we have a few dependencies in our code that have not been met.

  • The first error is caused by the use of the export keyword in our TypeScript code. Unfortunately, the export keyword and the import keyword, for that matter, are used for module resolution. In other words, if we import a library, the runtime must be able to find that library somewhere and understand how to import it. Exports are the other way around, where we are defining something as being exported, and the runtime must know how to register this with the module resolving routines.

  • The second error is due to our code importing the RxJS library, as the on function that we are using is defined in this library. What this means is that we need to include the RxJS library as a dependency within our library output.

Both of these errors can be resolved by packaging our code correctly, which we can do by building a self-contained module. We will use webpack for this, so let’s install the webpack npm library as follows:

npm install webpack --save-dev
npm install webpack-cli --save-dev

We have installed webpack and the webpack-cli package as developer dependencies. With webpack installed, we can now create a file at the root of the project named micro-event-bus/webpack.config.js, as follows:

Get hands-on with 1200+ tech skills courses.