I have an NPM package written in TypeScript which is designd to work with Node.js applications. I have classes in this package which have methods that are internal use only, although I cannot mark them as private because they are used by other components within the package. To solve this problem, I do not export the class from the project, and when I return an instance of the class to the caller, I type cast it as an interface which only has the publicly accessible methods.
This works fine, but if I want to break my project into smaller files, how can I do this without being forced to export my classes, and risk the misuse of my NPM module?
Here is a simplified example of what I am trying to do:
File: internal.ts
// Can I make this class not publicly accessible?
export class InternalClass {
constructor() {
}
public sharedMethod(): void {
// Accessible to users of the package
}
public protectedMethod(): void {
// Only for use within the package
}
}
File: external.ts
import { InternalClass } from "./internal";
export interface ExternalInterface {
sharedMethod(): void;
// protectedMethod is not available outside the package
}
export function makeInterface(): ExternalInterface {
return new InternalClass();
}
Any ideas for how to do this well would be greatly appreciated.
The way I do this is by controlling what exactly gets exposed by the npm package.
For example if my package.json looks like this:
{
....
"main": "dist/index.js",
"typings": "typings/index.d.ts",
....
}
then in the corresponding index.ts I can manually control what will be exposed (exported) as part of the package.
export * from "./lib/Helper";
export * from "./lib/Log";
import * as M from "./lib/Maps";
export {M as Maps};
If I have module/class that I do not want to be accessible "outside" - I simply do not export it as part of index.ts or its referenced children. This does not prohibit me though to import and use it internally in the same package.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With