js-libp2p icon indicating copy to clipboard operation
js-libp2p copied to clipboard

Compatibility with --experimental-strip-types

Open achingbrain opened this issue 1 year ago • 0 comments

Node.js supports stripping TypeScript types with the --experimental-strip-types flag. This flag was introduced in 22.6.0 and was turned on by default in 23.6.0.

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:

  • [x] a PR to aegir to enable the allowImportingTsExtensions tsconfig option
  • [x] upgrade 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.

achingbrain avatar Nov 07 '24 12:11 achingbrain