Home > Net >  Not able to integrate a standalone library in angular application
Not able to integrate a standalone library in angular application

Time:10-11

I have a standalone typescript library with the below code (based on 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 built the above code and packed to a tarball. and also installed the package to my angular application. I added the code to app.component.ts ngOnInit, I'm getting the below error

code:

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

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

I'm using prepack.js to pack it as a tarball. and using webpack to build the standalone library.

Update #1:

Instead of having this as a separate library, I created a library within my angular application using ng g library ... and used the same code. It works perfectly fine. But if I'm using it as a standalone project then I'm having this issue.

Update #2:

The code is perfectly fine, but the issue is with webpack. When I removed webpack and tried using parcelJS, it was working fine. Not sure, why webpack packed code has this error.

Update #3: This 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;
}

I tried to import in both ways

import { CodeLib } from 'libname' // just an example

and

const lib = require('libname') // just an example

But getting the same issue while tried to import in both ways. Any help is appreciated. Thanks.

CodePudding user response:

Finally found the issue. It's because of a small configuration mistake. I added two configurations to the output section of the webpack config file and it worked as expected. phew. finally.

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