What is the correct method for packaging and using a TypeScript library built with webpack?

Recently delving into the world of TypeScript, I find myself struggling to grasp how to create a TypeScript library that can be utilized in another TypeScript module through webpack.

This particular library is meant to be functional within a browser environment.

At present, my project structure and build output look like this:

lib
├── build
│   ├── typings // tsc output with declaration:true
│   │   ├── Bar.d.ts
│   │   └── Foo.d.ts
│   └── lib.bundle.js //webpack bundle file
├── src
│   ├── Bar.ts
│   └── Foo.ts
├── bower.json
├── package.json
└── tsconfig.json

Configuration for webpack:

webpackOptions = {
    resolve: { extensions: ['', '.ts'] },
    module: {
      loaders: [{ test: /\.ts$/, exclude: [/node_modules/,/out/,/.*\.d\.ts/],include:[/\.ts$/], loaders: ['ts-loader']}]
    },
    ts:{
      compilerOptions:compilerOptions
    },
    output: {
      library:"mylib",
      libraryTarget:'commonjs',
      filename: 'mylib.bundle.js'
    }
  }

tsconfig.json contents:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "sourceMap": true,
    "outDir":"out",
    "declaration": true
  },
  "exclude": [
    "node_modules",
    "bower_components",
    "typings/global",
    "build"
  ]
}

Example of Foo.ts:

export class Foo{
    foo(){}
}

Bar.ts code snippet:

import {Foo} from './Foo'
export class Bar{
    public foo:Foo = new Foo();
}

The resulting build output includes:

  • A webpack bundle
  • TypeScript declarations for each file

Now, here are some questions that arose:

  • How do I import/consume this library via bower in another browser application(using TypeScript and webpack)?
  • What import syntax should be used in an application that consumes this library(e.g. import .. from or require)?
  • Is it possible that using webpack for bundling the library may not be necessary at all?

UPDATE: Following @basarat's suggestion, I switched to NPM for managing local dependencies between TypeScript modules instead of using bower, and everything worked smoothly.

Answer №1

Perhaps it would be best to avoid using webpack for bundling a library altogether

My suggestion is to let the top-level application consumer handle the bundling process.

For example, consider the module csx available at https://github.com/basarat/csx. This module is not bundled in any specific way; it's simply a node module. If someone wants to use it in the browser, they will need to take care of the bundling themselves 🌹

More

https://basarat.gitbooks.io/typescript/content/docs/quick/nodejs.html

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Webpack fails to transmit watchOptions to the watcher

Having an issue with webpack and wondering if fixing it will require forking the repo. Also, seeking guidance on merging it back in. The problem arises when using the webpack npm module environment in a development virtual machine where code is edited on ...

Sporadic UnhandledPromiseRejectionWarning surfacing while utilizing sinon

Upon inspection, it appears that the objects failApiClient and explicitFailApiClient should be of the same type. When logging them, they seem to have identical outputs: console.log(failApiClient) // { getObjects: [Function: getObjects] } console.log(expli ...

Issue encountered while authenticating client secret from backend for newly created Stripe subscription

There seems to be an issue with confirming the client secret sent from the express backend to the frontend, specifically in a React Native-based mobile application. The clientSecret is being sent in the same manner as described above. On the frontend Rea ...

React-aria | Encountering a typescript error with input fields/textfields

Seeking assistance with using react-aria, specifically the useTextField feature. Despite following the documentation available at , I encountered an error related to the input element. Any help would be appreciated. Code import { AriaTextFieldOptions, use ...

Unable to set value using React Hook Form for Material-UI Autocomplete is not functioning

Currently, I am in the process of constructing a form using React-Hook-Form paired with Material-UI. To ensure seamless integration, each Material-UI form component is encapsulated within a react-hook-form Controller component. One interesting feature I a ...

The resend email feature isn't functioning properly on the production environment with next js, however, it works seamlessly in the development environment

import { EmailTemplate } from "@/components/email-template"; import { Resend } from "resend"; const resend = new Resend("myApiKey"); // this works only in dev // const resend = new Resend(process.env.NEXT_PUBLIC_RESEND_API_KE ...

Is TypeScript inadvertently including unnecessary files in its compilation?

In my configuration file, tsconfig looks like this: { "compilerOptions": { "module": "esnext", "target": "es6", "declaration": true, "outDir": "./dist", }, "include": [ "src/**/*" ] } Let's consider a simple source file f ...

What is the necessity of requiring a parameter with the type "any"?

There is a function in my code that takes a single parameter of type any: function doSomething(param: any) { // Code to handle the param } When I call this function without passing any arguments: doSomething(); An error is thrown saying: "Expected 1 ...

Tips on injecting configuration into forRoot

Is there a method to inject configuration object into AppModule's forRoot() function? How can I access the configService if there is no constructor within the module? config.yml: smtp: host: 'smtp.host.com' port: 10 secure: true aut ...

Having trouble resolving errors in Visual Studio Code after failing to properly close a parent function? Learn how to fix this issue

Here we have the code starting with the construct function followed by the parents function public construct() //child { super.construct; } protected construct() //parent { } The issue arises where I am not receiving an er ...

Troubleshooting: Prettier Extension Compatibility Issue in VS Code with Create-React-App and Typescript Template

I'm currently in the process of setting up my application using the Create-React-App startup package with the TypeScript template. Everything goes smoothly during the initial installation. However, when I attempt to use the Prettier Code Formatter ext ...

What is the reason behind TypeScript failing to provide type safety in a generic higher order component which introduces extra properties into React components?

I'm currently working on developing a versatile higher order component, but have encountered an issue with type safety not being enforced. Interestingly, when attempting the same implementation without using generics, the type safety is verified as ex ...

How to load a PFX certificate from a file in NodeJS

For my current project involving Node.JS and TypeScript, one of the key requirements is to encrypt the payload body using a PFX certificate read from a .pfx file. The certificate I have is named cert1.pfx, and my code necessitates utilizing this certifica ...

Route Handler 13 is encountering difficulties in retrieving data from the body in the (app/api/auth) endpoint

Whenever I attempt to retrieve the body from the new export async function POST( req: Request), it seems to come through as a stream instead of the expected content type. The route handler can be found in api/auth/signup See folder layout image export asyn ...

Unable to resolve TypeScript error: Potential 'undefined' object

Here is the code snippet that I am working with: const queryInput = useRef() const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault() if (queryInput && queryInput.current) { console.log(`queryInput.cur ...

An obstacle encountered when implementing feature module services in a controller for a Nest JS microservice

Recently, I developed a feature module named "user" which includes a controller, model, and services to interact with my postgres database. Despite setting up everything correctly, I encountered an error when trying to call userService from the feature mod ...

Expanding a component using the identical selector in Angular 2 / Angular-CLI

We are leveraging Angular to create a sleek component-based frontend for our primary application. Our various clients often request minor customizations to these core components. To maintain the integrity of our core code, we plan to store it in NPM packag ...

Tips for integrating an arrow function as a property in a functional programming approach using JavaScript or TypeScript

Suppose I were to create a constructor for a functional class with TypeA as an argument, and TypeB representing the type of the class itself. In such cases, I can implement it using: functionName(argument: TypeA): TypeB { this.property = argument; ...

Unable to pass a component property to a styled Material-UI Button

I have customized a MUI Button: const SecondaryButton = styled(Button)<ButtonProps>(({ theme }) => ({ ... })); export default SecondaryButton; When I try to use it like this: <label htmlFor="contained-button-file"> <input ...

Navigating through object keys in YupTrying to iterate through the keys of an

Looking for the best approach to iterate through dynamically created forms using Yup? In my application, users can add an infinite number of small forms that only ask for a client's name (required), surname, and age. I have used Formik to create them ...