Having difficulties incorporating a separate library into an Angular project

My typescript library contains the following code, inspired by this singleton example code

export class CodeLib {
    private static _instance: CodeLib;
    
    constructor() {
    }

    static get instance(): CodeLib {
        if(!this._instance){
            this._instance = new CodeLib();
        }

        return this._instance;
    }

    setToken(key: string): void {
        console.log('public key saved!', key);
        
    }
}

I have compiled the above code and created a tarball from it. After installing the package to my Angular application, I included the code in app.component.ts ngOnInit, only to encounter the error below:

error:

CodeLib.instance.setToken('Hello World');

ERROR TypeError: Cannot read properties of undefined (reading 'instance')

Despite successfully using the code within my Angular application as a separate library created with ng g library ..., the issue arises when attempting to utilize it as a standalone project.

The culprit seems to be webpack, as switching to parcelJS resolves the error. The conflicting behavior between webpack-packed code and parcelJS remains a mystery.

Here is my webpack.config.js:

const config = {
  entry: {
    index: path.resolve(__dirname, 'src/index.ts')
  },
  target: 'node',
  module: {
    rules: [
      test: /\.ts$/,
      exclude: [/node_modules/],
      loader: 'ts-loader'
    ]
  },
  resolve: {
    extensions: ['.ts', '.js']
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    chunkFilename: '[name].js',
    filename: '[name].js'
  },
  mode: 'production'
}

module.exports = () => {
  return config;
}

Attempts to import the code through both methods -

import { CodeLib } from 'libname'
and const lib = require('libname') - yield the same unresolved issue. Any insights would be greatly appreciated. Thank you.

Answer №1

After some digging, I identified the root cause of the problem. It turns out there was a minor configuration error in my webpack setup. By making a small change and adding two configurations to the output section of the webpack config file, everything started working properly. What a relief!

output: {
  path: path.resolve(__dirname, 'dist'),
  chunkFilename: '[name].js',
  filename: '[name].js',
  libraryTarget: 'umd', // <-- this and the line below resolved the issue
  globalObject: 'this'
}

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 is the purpose of implementing asynchronous loading for JavaScript in my webpack setup?

I am facing difficulties with handling unusual codes. I am trying to add some query parameters using $.ajaxPrefilter in all jQuery ajax requests. I came across the following code snippet which seems to ensure synchronous loading order, but in my entry.js ...

Observation reveals a lack of return value

I'm encountering an issue with user sign-in functionality. My setup involves using nativescript-angular in conjunction with a Rails 5 API that utilizes devise_token_auth for authentication. The strange thing is that, despite the server logs indicating ...

Looking to dynamically adjust row color based on status using ANGULAR 4

In my table, I have 6 columns: name, email, phone, company, status_1, and status_2. Both status_1 and status_2 can have two options: "1" or "0." My Requirement: I want to change the color of the row based on the following logic: if(status_1 is "1" ...

Create a custom data structure resembling a record, where certain keys are assigned specific value types

My objective is to establish a custom type resembling a record, where certain keys are designated for specific value types. The proposed object would look something like this: const o: TRec = { text: "abc", width: 123, height: 456, //...an ...

Generating Angular components dynamically in batch

I have a collection of diverse data objects: const arr = [ {type: 'CustomA', id: 1, label: 'foo'}, {type: 'CustomB', src: './images/some.jpg'} {type: 'CustomX', firstName: 'Bob', secondNa ...

Guide on creating a style instance in a component class using Material-UI and Typescript

After transitioning my function component to a class component, I encountered an error with makeStyle() from Material-UI as it violates the Rule of Hooks for React. The documentation for Material-UI seems to focus mainly on examples and information related ...

How can we efficiently determine if a background image is broken in Angular 5 and substitute it with a default image?

When working with Angular 2+, we often use the <img> tag to display images using a syntax like <img [src]="myDp" (error)="myDp='assets/media/user/default_dp.jpg'">, where myDp contains the relative path to the image on the server. Is ...

Remove all spaces from input fields in angular Typescript, excluding the enter key

I've encountered an issue where the code below removes all spaces, but it's also removing the enter key. Is there a way to remove only spaces and not affect the enter key? static stripDoubleSpaces(str: string): string { if (!!str) { ...

Saving selected language in Angular using ngx-translate

I am facing an issue with ngx-translate for translation. Whenever I select a language, it gets saved in localStorage. However, upon refreshing the page or navigating to another page, it reverts back to the default keys instead of the selected language. Be ...

What is the process for defining a type that retrieves all functions from a TypeScript class?

Imagine having a class called Foo class Foo { bar(){ // do something } baz() { // do something } } How can you define a type ExtractMethods that takes a class and returns an interface or type containing the class methods? For example: t ...

Tips for passing the indexes of an array within nested ngFor loops in Angular

I have a 2D grid in my component that is created using nested ngFor loops, and I want to make certain grid elements clickable under specific conditions so they can call a function. Is there a way for me to pass the index of the clicked array element to the ...

The attribute 'data' is not found in the type 'IntrinsicAttributes & IProps'. Error code: ts(2322)

I encountered the following issue: Error: Type '{ data: never; }' is not compatible with type 'IntrinsicAttributes & IProps'. The property 'data' does not exist on the type 'IntrinsicAttributes & IProps'. import { ...

Discover the inverse of Object Arrays interaction in TypeScript

My agent object has the following structure: agentObj = { "agentId": "saqib", "attributes": [ { "name": "Marketing", "type": "Boolean", }, { "name": "English", "type": "Profi ...

You must provide a secret or key in order to use the JwtStrategy

I have encountered the following error and I am unsure of its cause. Can you assist me? ERROR [ExceptionHandler] JwtStrategy requires a secret or key TypeError: JwtStrategy requires a secret or key at new JwtStrategy (C:\Users\wapg2\OneDriv ...

Utilizing CSS in Angular applications

I am currently working on an Angular 2 application and I am fairly new to Angular. I am facing an issue where my CSS does not seem to be applying properly. There are three key files involved: landing.component.html landing.component.scss landing.compone ...

Develop a mobile application utilizing reactjs based on my website, not native

I am in the process of creating a mobile application that mirrors my existing website built with reactjs. As I was researching on reactjs, I wondered if it is possible to convert my reactjs code from the website into code for the mobile application. Any s ...

Leverage React Application with NodeJS backend within your network environment

I'm currently working on a React app (latest React version) with a NodeJS backend that is running locally. Now, I am looking to access this React app and its backend from other devices within my home network. How can I achieve this? Here is the pack ...

Troubleshooting Typescript with Chrome when packaged by Webpack on Visual Studio 2017 using .NET Core 2.2

Many questions have been asked about debugger issues in Visual Studio 2017 with TypeScript and Webpack. Despite the common answer being that it should work by default, my debugger is still not functioning properly. I am new to TypeScript and Webpack, so I ...

minimize the size of the indigenous foundation input field

Currently incorporating this code snippet into my application: <Item fixedLabel> <Input style={{ width: 0.5 }}/> </Item> The fixedLabel element is extending the entire width of the screen. I have attempted adju ...

Error encountered when using withRouter together with withStyles in Typescript on ComponentName

Building an SPA using React with Typescript and Material UI for the UI framework. Stuck on a recurring error across multiple files - TS2345 Typescript error: Argument of type 'ComponentType<Pick<ComponentProps & StylesProps & RouteCompo ...