libp2p / js-libp2p

The JavaScript Implementation of libp2p networking stack.
https://libp2p.github.io/js-libp2p/
Other
2.34k stars 447 forks source link

Compatibility with --experimental-strip-types #2812

Open achingbrain opened 2 weeks ago

achingbrain commented 2 weeks ago

Node.js supports stripping TypeScript types with the --experimental-strip-types flag. This flag was introduced in 22.6.0 and will be turned on by default soon(tm) and backported to older versions.

It takes a TypeScript file like:

export function myFunction (name: string): string {
  return `hello ${name}`
}

And simply replaces any TypeScript specific syntax with whitespace:

export function myFunction (name        )         {
  return `hello ${name}`
}

This means Node.js can run TypeScript files without a transpilation/validation step, without depending on tsc or having to know about a project's special unique tsconfig.json setup, and also without needing to add source maps, since all the line numbers/locations are unchanged between the .ts source and the executed JavaScript.

There are a few caveats:

  1. Preprocessing .ts files like this only happens in the current project, not in the node_modules folder so projects will still need to ship transpiled .js files (this will likely apply to monorepo sibling packages too, they'll still have to be built before a dependant sibling can run their code)
  2. It'll only run on .ts files, so all import statements must import .ts
  3. Features that require code transforms by tsc require an additional --experimental-transform-types flag

For us only the last two things will cause headaches.

The replacement of .js with .ts will need a PR to aegir to enable the allowImportingTsExtensions tsconfig option and likely an upgrade to the typescript dependency to 5.7.x when it is available, after that it is a relatively simple find & replace operation.

For code that requires transpilation, we only have a few enums in the codebase - I don't think we use any other features that need it. Enabling the --experimental-transform-types flag will cause source maps to be generated which we may wish to avoid - we may be better of refactoring our enums to just be regular JS objects.