developit / microbundle

📦 Zero-configuration bundler for tiny modules.
https://npm.im/microbundle
MIT License
8.04k stars 362 forks source link

Apply mangle transformation on TypeScript types #923

Closed aralroca closed 2 years ago

aralroca commented 2 years ago

mangle.json

{
  "minify": {
    "mangle": {
      "properties": {
        "regex": "^_"
      }
    },
    "compress": {
      "hoist_vars": true,
      "reduce_funcs": true
    }
  },
  "props": {
    "cname": 6,
    "props": {
      "$_subscribe": "s",
      "$_notify": "n",
      "$_unsubscribe": "u"
    }
  }
}

It's replacing _subscribe to s, _notify to n, _unsubscribe to u. This is OK! However, the TypeScript type is not replaced:

export declare type Subscription<S extends Store> = {
    _subscribe(path: string, listener?: Listener<S>): void;
    _unsubscribe(path: string, listener?: Listener<S>): void;
    _notify(path: string, params: Params<S>): void;
};

I think the change should also be made on types.

It's a type for internal stuff, but there is support for adding plugins in my library and therefore they could use the internal types to touch subscriptions (s, u and n).

rschristian commented 2 years ago

Looked into this a bit today, and I don't think it's really going to be possible (at least not without a fair bit of work and/or forking).

Firstly, in order for rollup-plugin-typescript2 to correctly handle the users' declarationDir in their tsconfig.json, it essentially needs to write the output .d.ts directly to the disk, bypassing the opportunity for any other Rollup plugins to access this (rollup-plugin-typescript2, useTsconfigDeclarationDir option).

Secondly, even if we were to throw that functionality away (which would be a big loss), the .d.ts files are only generated after the Terser has been ran, it looks like.

Your best bet is likely to run a mangling script separately post-build.

aralroca commented 2 years ago

Ok, thank you very much @rschristian! the issue was if it could be done without big loss. If it's not possible, no problem, then I will use the script you mentioned!

rschristian commented 2 years ago

Yeah, sorry for that. Would love if it can be done, and it's certainly possible I'm missing something in my analysis.

It looks like Preact's types suffer from this too but I'm not knowledgeable enough to know whether or not those are ever publicly exposed and used. I'll do some more poking around tomorrow to see if they are and how that's done, though it might just be a case of ignoring the TS types.