Convert Figma logo to code with AI

cevek logottypescript

Over TypeScript tool to use custom transformers in the tsconfig.json

1,531
56
1,531
23

Top Related Projects

100,112

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

:books: The definitive guide to TypeScript and possibly the best TypeScript book :book:. Free and Open Source 🌹

12,836

TypeScript execution and REPL for node.js

6,922

A Jest transformer with source map support that lets you use Jest to test projects written in TypeScript.

TypeScript loader for webpack

31,086

Rust-based platform for the Web

Quick Overview

TTYPescript is a TypeScript transformer that allows you to use custom transformers in your TypeScript compilation process. It extends the capabilities of the TypeScript compiler by enabling the use of plugins to modify the Abstract Syntax Tree (AST) during compilation, providing additional flexibility and power to your TypeScript projects.

Pros

  • Enables the use of custom transformers in TypeScript compilation
  • Allows for powerful code modifications and optimizations
  • Integrates seamlessly with existing TypeScript tooling
  • Supports a wide range of transformation use cases

Cons

  • Requires additional setup and configuration
  • May introduce complexity to the build process
  • Limited documentation and examples for some advanced use cases
  • Potential for performance impact on large projects

Code Examples

  1. Basic transformer setup:
// ttypescript.json
{
  "compilerOptions": {
    "plugins": [
      { "transform": "my-custom-transformer" }
    ]
  }
}
  1. Custom transformer example:
// my-custom-transformer.ts
import * as ts from 'typescript';

export default function(program: ts.Program) {
  return (ctx: ts.TransformationContext) => {
    return (sourceFile: ts.SourceFile) => {
      function visit(node: ts.Node): ts.Node {
        if (ts.isStringLiteral(node)) {
          return ts.createStringLiteral(node.text.toUpperCase());
        }
        return ts.visitEachChild(node, visit, ctx);
      }
      return ts.visitNode(sourceFile, visit);
    };
  };
}
  1. Using the transformer in a TypeScript file:
// example.ts
const message = "hello, world!";
console.log(message);

// After transformation:
// const message = "HELLO, WORLD!";
// console.log(message);

Getting Started

  1. Install TTYPescript:

    npm install -D ttypescript typescript
    
  2. Create a ttypescript.json configuration file:

    {
      "compilerOptions": {
        "plugins": [
          { "transform": "./path/to/your/transformer.ts" }
        ]
      }
    }
    
  3. Run TTYPescript instead of TypeScript:

    ttsc
    

Competitor Comparisons

100,112

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

Pros of TypeScript

  • Official Microsoft project with extensive resources and community support
  • Comprehensive language features and continuous development
  • Seamless integration with popular IDEs and development tools

Cons of TypeScript

  • Slower compilation times for large projects
  • Limited ability to extend or customize the compiler
  • Steeper learning curve for developers new to static typing

Code Comparison

TypeScript (standard usage):

function greet(name: string): string {
  return `Hello, ${name}!`;
}

TTYPescript (with custom transformer):

import { transform } from 'my-custom-transformer';

@transform()
function greet(name: string): string {
  return `Hello, ${name}!`;
}

TTYPescript allows for custom transformers to be applied directly in the code, enabling additional compile-time modifications and optimizations. This feature is not available in standard TypeScript without external build tools.

While TypeScript provides a robust and widely-adopted solution for adding static typing to JavaScript, TTYPescript offers more flexibility for advanced users who need to extend the compiler's functionality. However, TypeScript's extensive ecosystem and official backing make it the more popular choice for most projects.

:books: The definitive guide to TypeScript and possibly the best TypeScript book :book:. Free and Open Source 🌹

Pros of typescript-book

  • Comprehensive learning resource for TypeScript
  • Regularly updated with new TypeScript features and best practices
  • Includes practical examples and explanations for various TypeScript concepts

Cons of typescript-book

  • Not a tool or library, but rather educational content
  • May require more time investment to learn compared to using a tool like ttypescript

Code Comparison

typescript-book (example of TypeScript interface):

interface Person {
  name: string;
  age: number;
}

ttypescript (example of transformer usage):

import { createTransformer } from 'ttypescript';

const transformer = createTransformer({
  before: [/* transformers */],
});

Summary

typescript-book is an extensive educational resource for learning TypeScript, offering in-depth explanations and examples. It's ideal for developers looking to deepen their understanding of TypeScript concepts and best practices. On the other hand, ttypescript is a tool that extends TypeScript's functionality through custom transformers, allowing for more advanced code manipulation. While typescript-book provides knowledge, ttypescript offers practical enhancements to the TypeScript compilation process.

12,836

TypeScript execution and REPL for node.js

Pros of ts-node

  • More widely adopted and actively maintained
  • Supports both REPL and script execution
  • Integrates well with popular testing frameworks

Cons of ts-node

  • Can be slower for large projects due to on-the-fly compilation
  • May require additional configuration for complex TypeScript setups

Code Comparison

ts-node:

// Execute TypeScript directly
ts-node script.ts

// Use in REPL mode
ts-node

ttypescript:

// Compile TypeScript with custom transformers
ttsc

// Use with ts-node
ts-node -C ttypescript script.ts

Key Differences

  • ts-node focuses on runtime execution of TypeScript, while ttypescript emphasizes compile-time transformations
  • ts-node has broader ecosystem support, whereas ttypescript offers more flexibility in code transformations
  • ts-node is easier to set up for quick TypeScript execution, while ttypescript requires additional configuration for custom transformers

Use Cases

ts-node is ideal for:

  • Rapid prototyping and development
  • Running TypeScript in CI/CD pipelines
  • Integration with testing frameworks

ttypescript is better suited for:

  • Projects requiring custom AST transformations
  • Scenarios where compile-time modifications are necessary
  • Advanced TypeScript configurations with specialized build processes
6,922

A Jest transformer with source map support that lets you use Jest to test projects written in TypeScript.

Pros of ts-jest

  • Seamless integration with Jest, a popular JavaScript testing framework
  • Automatic TypeScript compilation and transformation during test execution
  • Extensive configuration options for fine-tuning TypeScript behavior in tests

Cons of ts-jest

  • Limited to Jest testing environment, not suitable for other use cases
  • May have performance overhead due to runtime compilation
  • Requires additional setup and configuration compared to native TypeScript

Code Comparison

ts-jest configuration:

{
  "jest": {
    "preset": "ts-jest",
    "testEnvironment": "node"
  }
}

ttypescript usage:

{
  "compilerOptions": {
    "plugins": [{ "transform": "typescript-transform-paths" }]
  }
}

ts-jest focuses on integrating TypeScript with Jest for testing purposes, while ttypescript is a more general-purpose tool for extending TypeScript's capabilities through custom transformers. ts-jest provides a smoother testing experience for TypeScript projects using Jest, but is limited to that specific use case. ttypescript offers more flexibility for various TypeScript transformations but requires more manual setup and integration with other tools.

ts-jest is ideal for projects heavily reliant on Jest for testing, while ttypescript is better suited for projects requiring custom TypeScript transformations across different build and test environments.

TypeScript loader for webpack

Pros of ts-loader

  • More widely adopted and mature project with a larger community
  • Seamless integration with webpack ecosystem
  • Supports both TypeScript and JavaScript files

Cons of ts-loader

  • Slower compilation times for large projects
  • Requires additional configuration for advanced TypeScript features

Code Comparison

ts-loader configuration:

module.exports = {
  module: {
    rules: [
      { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ }
    ]
  }
}

ttypescript usage:

const ttypescript = require('ttypescript');
ttypescript.createProgram(files, options);

Key Differences

  • ts-loader is specifically designed for webpack integration, while ttypescript is a more general-purpose TypeScript compiler
  • ttypescript allows for custom transformers, providing more flexibility in code generation
  • ts-loader handles file watching and incremental compilation out of the box, whereas ttypescript requires additional setup for these features

Use Cases

  • Choose ts-loader for seamless webpack integration and straightforward TypeScript compilation in web projects
  • Opt for ttypescript when you need custom transformers or more control over the compilation process, especially in non-webpack environments
31,086

Rust-based platform for the Web

Pros of swc

  • Significantly faster compilation and transpilation speeds
  • Written in Rust, offering better performance and memory safety
  • Supports more modern JavaScript features and syntax

Cons of swc

  • Less mature and potentially less stable than ttypescript
  • May have fewer plugins and community-contributed extensions
  • Learning curve for developers unfamiliar with Rust ecosystem

Code Comparison

ttypescript:

import ts from 'typescript';

const program = ts.createProgram(['file.ts'], {});
const sourceFile = program.getSourceFile('file.ts');
const result = ts.transpileModule(sourceFile.text, {
  compilerOptions: { module: ts.ModuleKind.CommonJS }
});

swc:

const swc = require('@swc/core');

const result = swc.transformSync(code, {
  jsc: {
    parser: {
      syntax: "typescript",
    },
    target: "es2015"
  },
  module: {
    type: "commonjs"
  }
});

Both ttypescript and swc aim to improve TypeScript compilation and transpilation processes. ttypescript extends the official TypeScript compiler, providing a familiar environment for TypeScript developers. It offers plugin support and integrates well with existing TypeScript tooling.

swc, on the other hand, is a complete rewrite of the TypeScript compiler in Rust. It prioritizes speed and performance, making it an excellent choice for large-scale projects or environments where compilation time is critical. However, its ecosystem is still growing, and it may lack some of the more niche features or plugins available in ttypescript.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Deprecation Notice

ttypescript is deprecated. It currently works with TS below 5.0, but it will not be updated.

For TypeScript 5+, please use ts-patch.


npm version Build Status

ttypescript

What it is

Currently TypeScript doesn't support custom transformers in the tsconfig.json, but supports it programmatically.

And there is no way to compile your files using custom transformers using tsc command.

TTypescript (Transformer TypeScript) solves this problem by patching on the fly the compile module to use transformers from tsconfig.json.

Instead of tsc and tsserver, use ttsc and ttsserver wrappers. This wrappers try to use locally installed typescript first.

No version lock-ins - typescript used as peer dependency.

How to install

npm i ttypescript -D

ttypescript uses your installed typescript in your node_modules

How to use

tsconfig.json

Set a transformer path to the tsconfig.json in compilerOptions section plugin array:

{
    "compilerOptions": {
        "plugins": [
            { "transform": "transformer-module" },
        ]
    }
}

plugin entries described in PluginConfig:

export interface PluginConfig {
    /**
     * Path to transformer or transformer module name
     */
    transform?: string;

    /**
     * The optional name of the exported transform plugin in the transform module.
     */
    import?: string;

    /**
     * Plugin entry point format type, default is program
     */
    type?: 'program' | 'config' | 'checker' | 'raw' | 'compilerOptions';

    /**
     * Should transformer applied after all ones
     */
    after?: boolean;

    /**
     * Should transformer applied for d.ts files, supports from TS2.9
     */
    afterDeclarations?: boolean;
    /**
     * any other properties provided to the transformer as config argument
     * */
    [options: string]: any;
}

You just need to add the transform block with optional import, type, after, afterDeclarations and plugin-related options.

transform can accept npm module or local file path (.ts or .js) related to tsconfig.json

PluginConfig.type

Because currently transformers can run only programmatically, most of them use factory wrapper with different signatures. For the possible to work with any of them you can specify type in the plugin config.

By default will be used a program type.

program

If the transformer has a factory signature using program as first argument:

(program: ts.Program, config?: PluginConfig) => ts.TransformerFactory
where 
ts.TransformerFactory = (context: ts.TransformationContext) => (sourceFile: ts.SourceFile) => ts.SourceFile

Plugin config entry: { "transform": "transformer-module" }.

config

For the signature with transformer's config:

(config: PluginConfig) => ts.TransformerFactory

Plugin config entry: { "transform": "transformer-module", type: "config" }.

checker

For the signature with ts.TypeChecker:

(checker: ts.TypeChecker, config?: PluginConfig) => ts.TransformerFactory

Plugin config entry: { "transform": "transformer-module", type: "checker" }.

raw

For the signature without factory wrapper:

ts.TransformerFactory

Plugin config entry: { "transform": "transformer-module", type: "raw" }.

compilerOptions

(compilerOpts: ts.CompilerOptions, config?: PluginConfig) => ts.TransformerFactory

Plugin config entry: { "transform": "transformer-module", type: "compilerOptions" }.

{
    "compilerOptions": {
        "plugins": [
            { "transform": "transformer-module", "someOption1": 123, "someOption2": 321 },
            { "transform": "./transformers/my-transformer.ts" },
            { "transform": "transformer-module", "after": true },
            { "transform": "transformer-module", "afterDeclarations": true },
            { "transform": "transformer-module", "type": "ls" }
        ]
    },
}

Command line

Like usual tsc, all arguments work the same way.

ttsc

ts-node

ts-node --compiler ttypescript index.ts
or
ts-node -C ttypescript index.ts

Parcel

Just install a parcel plugin

npm i parcel-plugin-ttypescript

Webpack

    {
        test: /\.(ts|tsx)$/,
        loader: require.resolve('awesome-typescript-loader'),
        // or
        loader: require.resolve('ts-loader'),
        options: {
            compiler: 'ttypescript'
        }
    }

Rollup

// rollup.config.js
import ttypescript from 'ttypescript'
import tsPlugin from 'rollup-plugin-typescript2'

export default {
    // ...
    plugins: [
        // ...
        tsPlugin({
            typescript: ttypescript
        })
    ]
}

VS Code

If you want to compile your project with VS Code task runner you need to overwrite the config typescript.tsdk to path of the installed ttypescript:

"typescript.tsdk": "/usr/local/lib/node_modules/ttypescript/lib",
or 
"typescript.tsdk": "node_modules/ttypescript/lib",

Jest, ts-jest

module.exports = {
  // [...]
  globals: {
    'ts-jest': {
      compiler: 'ttypescript'
    }
  }
};

or in package.json

{
  "jest": {
    "globals": {
      "ts-jest": {
        "compiler": "ttypescript"
      }
    }
  }
}

Transformers

You can use transformers written in ts or js

// transformer1-module
import * as ts from 'typescript';
export default function(program: ts.Program, pluginOptions: {}) {
    return (ctx: ts.TransformationContext) => {
        return (sourceFile: ts.SourceFile) => {
            function visitor(node: ts.Node): ts.Node {
                // if (ts.isCallExpression(node)) {
                //     return ts.createLiteral('call');
                // }
                return ts.visitEachChild(node, visitor, ctx);
            }
            return ts.visitEachChild(sourceFile, visitor, ctx);
        };
    };
}

Examples of transformers:

{ "transform": "ts-nameof", type: "raw"}

{ "transform": "ts-optchain/transform" }

{ "transform": "ts-transform-asset" }

{ "transform": "ts-transform-auto-require" }

{ "transform": "ts-transform-css-modules/dist/transform", type: "config" }

{ "transform": "ts-transform-graphql-tag/dist/transformer" }

{ "transform": "ts-transform-img/dist/transform", type: "config" }

{ "transform": "ts-transform-react-intl/dist/transform", import: "transform", type: "config" }

{ "transform": "ts-transformer-enumerate/transformer" }

{ "transform": "ts-transformer-keys/transformer" }

{ "transform": "ts-transformer-minify-privates" }

{ "transform": "typescript-is/lib/transform-inline/transformer" }

{ "transform": "typescript-plugin-styled-components", type: "config" }

{ "transform": "typescript-transform-jsx" }

{ "transform": "typescript-transform-macros" }

{ "transform": "typescript-transform-paths" }

{ "transform": "@zerollup/ts-transform-paths" }

{ "transform": "@zoltu/typescript-transformer-append-js-extension" }

{ "transform": "@magic-works/ttypescript-browser-like-import-transformer" }

{ "transform": "typescript-transform-react-jsx-source" }

{ "transform": "ts-transformer-remove-named-export" }

{ "transform": "ts-transformer-export-default-name" }

{ "transform": "ts-transformer-inline-file/transformer" }

{ "transform": "ts-transformer-strip-const-enums", "entrySourceFiles": ["./src/index.ts" }

{ "transform": "ts-transformer-properties-rename", "entrySourceFiles": ["./src/index.ts"] }

{ "transform": "tsc-progress", "name": "TSC", "color": "green" }

Tutorial how to write a typescript transformer

Example

An example project is in the example directory

License

MIT License

NPM DownloadsLast 30 Days