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.