Reputation: 6544
I am building a library in typescript that is being published via npm.
In the index.ts, which is the starting point of the library, all the public classes and enums are exported.
import { MyClass } from './internal/my-class'
import { MyEnum } from './internal/my-enum'
export { MyClass, MyEnum }
This works well, but I noticed that users are able to import internal functions/classes etc. as well by using a direct path to the file.
// in a project that installed my library as an npm dependency
import { InternalClass } from 'my-lib/dist/internal/internal-class'
Is there a way to prevent this?
I need to "export" InternalClass
because I'm importing and using it throughout my library, but I don't want to expose it publicly. I tried using namespaces, but couldn't really get it to work.
Upvotes: 22
Views: 4914
Reputation: 474
You should set the stripInternal
flag in your tsconfig.json
(or from the command line) to true
and use tsdoc comments with the @internal
tag.
// internal/my_file.ts
/** @internal */
export function myInternalFunction() {}
Note that this will remove the function from the type declarations, so it that it will not autocomplete in editors, but if you really need to hide internal details I suggest you bundle your code using Rollup with the TypeScript plugin.
Upvotes: 18
Reputation: 2420
Using microbundle or similar tools to bundle your package. It should generate 1 file and your users can only import from that entry point.
Upvotes: 3
Reputation: 3710
I don't think you can.
I suppose you can use TS's modules to compile into JS's IIFE, as described by Lucas Morgan here, but I there's not much point doing that. If you publish open source, there's no stopping anyone from extracting any part of your code.
Upvotes: -2