Encountering errors pertaining to undefined exports while attempting to package a TypeScript library using webpack

In the process of developing my TypeScript library, I encountered an issue with bundling it using Webpack. Despite trying different configurations and loaders like ts-loader and awesome-ts-loader, I could not get the bundled package to work properly. Every time I attempted to import the bundled package, it returned "undefined."

Here is an excerpt from my tsconfig.json file:

{
    "compilerOptions": {
        "declaration": true,
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "es6",
        "target": "es6",
        "resolveJsonModule": true,
        "moduleResolution": "node"
    },
    "exclude": [
        "node_modules"
    ]
}

I also included my webpack configuration below:

const path = require('path');

module.exports = {
    entry: './src/index.ts',
    mode: 'production',
    module: {
        rules: [
            {
                test: /\.ts$/,
                use: 'ts-loader',
                exclude: '/node_modules/'
            }
        ]
    },
    resolve: {
        extensions: ['.ts']
    },
    output: {
        filename: 'index.js',
        path: path.resolve(__dirname, 'dist'),
        library: '',
        libraryTarget: 'commonjs2',
        libraryExport: 'default'
    }
};

Despite numerous attempts and hours of troubleshooting, I have not been able to resolve this issue. If anyone has any insights or suggestions that I have not already tried, I would greatly appreciate it.

Thank you.

Answer №1

Dealing with a similar issue, I found the solution that worked for me:

Update your webpack configuration in this manner:

output: {
  ...
  libraryTarget: 'umd',
  library: 'MyCustomPackageName',
  ...
}

Make adjustments in tsconfig.json as well:

compilerOptions: {
  ...
  "lib": ["es2015", "dom"],
  ...
}

Answer №2

For newcomers to the world of ts/js npm library development with webpack, it may not be immediately clear that during the build process, webpack automatically applies a set of optimizations that eliminate unused code.

When developing a library, it is important to explicitly instruct webpack not to remove your exports: https://webpack.js.org/guides/author-libraries/

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

What limitations do we face when trying to change the objects received by a component through @input() in Angular?

Recently, I made the leap from angular 7 to angular 11 in my app. Everything was running smoothly until I decided to incorporate angular universal for server-side rendering. Shortly after implementing server-side rendering, a flurry of errors cropped up, ...

Issues arise when trying to use additional loaders with Storybook 6.x and Vue 2

Moving over to Storybook 6.4 I am working on a story that involves loading a Vue component, but I keep encountering errors: ModuleParseError: Module parse failed: Unexpected token (92:0) File was processed with these loaders: * ./node_modules/vue-docgen- ...

File Locking Issue Between Gulp and Visual Studio: Understanding the Problem

Previously, our team utilized Bower to manage SASS and JavaScript packages. However, we have recently shifted to NPM for package management and Gulp for bundling and minification. The challenge we face now is encountering locked files when running Gulp tas ...

Differences in mounted volumes between using "up" and "run" in docker-compose

Update Alert 2: I've developed a demo project on GitHub to replicate this issue. After further testing, the scenario is slightly different from what I initially explained. Below you'll find the details of the README I created on the GitHub repos ...

Embedding images using a blob or base64 format does not function properly on iOS devices

I'm facing an issue with setting the src of an img tag to display an image. The code snippet below works fine on android, mac, and windows, but it is not functioning correctly on iOS: let base64Image = pageModel.image; this.$currentPageImage.src = `da ...

The module '@npmcorp/copy' is not locatable by NPM

I encountered this issue while attempting to install Parsoid on my Windows system, and I also faced the same problem when trying to install other packages. 0 info it worked if it ends with ok 1 verbose cli [ 'C:\\Program Files\\no ...

Enhance the functionality of angular-material buttons by incorporating dynamic loading animations into

I am currently working on a solution in Angular 12 to disable a button (and show a spinner) when it is clicked, until the API responds. To achieve this, I plan to follow a similar approach to the angular-material button implementation. Essentially, I want ...

Leveraging FormControlName in Typescript to Interact with HTML Components in Angular 4

How can I use FormControlName to access HTML elements in typescript? Typically, I am able to access HTML elements using their ID. For example: var element = document.getElementById("txtID") But is it possible to access the element without using its ID a ...

Retrieve the outermost shell of the VUEjs wrapper test-utils

While working on a VueJS test, I encountered an issue where accessing the outermost layer of HTML seemed impossible. No matter what methods I tried, the outermost layer was always ignored. Is there a way to gain access to this outermost layer so that I c ...

What is the rationale behind Yeoman's decision to utilize Bower alongside npm instead of solely relying

Currently diving into the world of these tools, I am still in the process of unraveling their complex dependencies. While Yeoman serves as a client for npm with some "wizard" capabilities and automatically installs generator dependencies, I find myself qu ...

Is it possible for me to listen to an AngularJS event using regular JavaScript, outside of the Angular framework?

Is it possible to listen to an event triggered in AngularJS using regular JS (outside of Angular)? I have a scenario where an event is being emitted using RxJS in Angular 2. Can I observe that event from pure JS? Here's some example pseudo code: imp ...

A guide on integrating a vue-concurrency Task Creator with argument support

I've been grappling with my Vue 3 / TypeScript app and the vue-concurrency library. Everything is nearly in place, but configuring a Task Creator to accept arguments has proven to be quite challenging. Following the Task Creators pattern outlined in ...

Definition of a Typescript Global.d.ts module for a function that is nested within another function

Simply put, I have a npm module that exports a function along with another function attached to it: // @mycompany/module ... const someTool = (options) => { // do some cool stuff }; someTool.canUseFeature1 = () => { return canUseSomeFeature1(); ...

Is it possible to dynamically assign class properties from an array in JavaScript/TypeScript?

Greetings for the assistance in advance. Currently, I am working with TypeScript, but I believe any JS solution will suffice. I aim to create something akin to the following: class ExcelData { 'Id 1': items[0].id, 'Quantity 1': item ...

Encountering a hitch while trying to deploy to Elastic Beanstalk due to an N

I am trying to deploy my node.js application on Elastic Beanstalk using a standard free tier t2.micro instance. However, I encountered an error message during the deployment process: "Cannot find application npm debug log at /tmp/deployment/applicati ...

I'm having trouble accessing the localhost, could someone please assist me in resolving this issue?

I'm not quite sure what's happening with my node command. I'm new to this so any help would be appreciated! ...

Retrieving information stored in a FormBuilder through the HTML

Once I set up a FormBuilder during the onInit Lifecyle: surveyForm: FormGroup; ngOnInit(): void { this.surveyForm = this.formBuilder.group({ 'surveyTitle': new FormControl(null), 'surveyDescription': new FormControl(n ...

Ubuntu installation of the Gekko Auto Trading bot encountered a technical error

I am fairly new to coding in Ubuntu and attempting to set up the Gekko auto trading bot on a web server that I created. Following instructions from a website, I have completed all the steps. However, when I try to start the service using: node gekko --ui ...

Developing a GraphQL application with NestJS integrating the Passport LinkedIn strategy

Currently, my nestjs application is up and running on typescript, Graphql, Postgres with Jwt strategy all set. Now, I am looking to integrate the LinkedIn strategy into it. However, I'm unsure about where to begin as most available packages like do no ...

Vue app: ESLint throwing error for undefined global variable in component during npm run serve

In my main.js file, I am initializing a new Vue instance on the window object: window.todoEventBus = new Vue() Within my components, I am attempting to access this global todoEventBus object like so: created() { todoEventBus.$on('pluralise&apos ...