Code Monkey home page Code Monkey logo

ttypescript's Introduction

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

ttypescript's People

Contributors

alexgorbatchev avatar cevek avatar danielpza avatar dsherret avatar gfx avatar hitkodev avatar huafu avatar igorbek avatar jack-works avatar jiangweixian avatar jirutka avatar mdmitry01 avatar micahzoltu avatar mikeyhew avatar nonara avatar oscard0m avatar salvatorepreviti avatar samchon avatar slurptheo avatar supernavix avatar sveyret avatar timocov avatar zerkalica avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ttypescript's Issues

ttypescript with transform plugins

1.5.7 is working and transformed paths (by command line ttsc --project ./tsconfig.json) with custom transformers (e.g. @zerollup/ts-transform-paths) but latest (2.5.2) is not

Support running transforms on all referenced projects with the --build option

I have a monorepo where I have configured each package to be built by ttsc -b. I need tsconfig alias paths to be transformed to relative paths using https://www.npmjs.com/package/@zerollup/ts-transform-paths module. Currently building a dependent project with ttsc doesn't run the transforms on the dependency packages. The only way is to manually build all packages in the order of dependencies. Considering tsc already builds them in the order, adding this support will be a huge step in solving the dreaded mono-repo holy grail problems.

Please let me know if there are any known workarounds.

Ship with source maps.

Rather than coming in here and asking questions for help, I was trying to help myself by stepping through the code to see if I could figure out what was going wrong. Unfortunately, ttypescript does not ship with source maps, so I'm left stepping through generated JS code which is quite difficult to read.

Consider adding sourceMaps: true and inlineSources: true to tsconfig.json of this project so the shipped package includes everything necessary to step through it neatly in a modern debugger.

Missing changelog entries and git tags

It looks like there is some releases after 1.5.5 (the latest version is 1.5.7), but no changelog entries and git tags is found in the repo/changelog file.

Suggestion: include ts-optchain as example transformer

We have built a custom transformer to support optional chaining in TypeScript: https://github.com/rimeto/ts-optchain

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

ts-optchain/transform automatically converts the code:

  const obj: T = { /* ... */ };
  const value = oc(obj).propA.propB.propC(defaultValue);

...into:

  const obj: T = { /* ... */ };
  const value =
    (obj != null && obj.propA != null && obj.propA.propB != null && obj.propA.propB.propC != null)
      ? obj.propA.propB.propC
      : defaultValue;

Would appreciate a cross-link!

process.cwd() won't find peer dependency if located in other directory

line 8 /lib/tsc.js assumes the peer typescript dependency is in same directory as where the process began. it would be great to have an optional arg for indicating where exactly the typescript peer dependency is.

When I cd ./app and run ttsc, ttsc can't find the peer dependency from ./build/node_modules

projects/
   tsconfig.base.json
   build/
        node_modules/typescript/
   app/
        tsconfig.json (extends tsconfig.base.json)
   admin/
        tsconfig.json (extends tsconfig.base.json)
   core/
        tsconfig.json (extends tsconfig.base.json)

Any way to ignore some diagnostics?

I'm trying to implement transformer for operators overloading. It does work. But I can't get rid from diagnostic errors. Is there any way it could be done?

Simple transformer:

export default function (program: ts.Program, config?: PluginConfig) {
  const diagnostics = ts.getPreEmitDiagnostics(program);
  return (ctx: ts.TransformationContext) => {
    return (sourceFile: ts.SourceFile) => {
      function visitor(node: ts.Node): ts.Node {
        if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken) {
              console.log('Found plus in:', type.getSymbol().escapedName);
              return ts.createCall(
                ts.createPropertyAccess(node.left, '__add'),
                [], [node.right]
              );
            }
          }
        }
        return ts.visitEachChild(node, visitor, ctx);
      }
      return ts.visitEachChild(sourceFile, visitor, ctx);
    };
  };
}

getting "SyntaxError: Cannot use import statement outside a module" error using ts-node with -C typescript option

I was using ts-node with tsconfig-paths like this:

"dev:ts-node": "ts-node -r tsconfig-paths/register src/start.ts",

and everything worked fine. Then I tried to use it with ttypescript to get rid of the tsconfig-paths dependency, like it's shown here: https://github.com/cevek/ttypescript#ts-node:

    "dev:ts-node": "ts-node -C ttypescript src/start.ts",

But when I try it I get the following error:

C:\data\devel\apps\sgte-it\coordinacion\juridicos\wspjn\src (master -> origin)
ฮป npm run dev:ts-node

> [email protected] dev:ts-node C:\data\devel\apps\sgte-it\coordinacion\juridicos\wspjn
> ts-node -C ttypescript src/start.ts

C:\data\devel\apps\sgte-it\coordinacion\juridicos\wspjn\src\app.ts:1
import express from 'express'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:881:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:962:10)
    at Module.load (internal/modules/cjs/loader.js:798:32)
    at Function.Module._load (internal/modules/cjs/loader.js:711:12)
    at Module.require (internal/modules/cjs/loader.js:838:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (C:\data\devel\apps\sgte-it\coordinacion\juridicos\wspjn\src\start.ts:5:1)
    at Module._compile (internal/modules/cjs/loader.js:945:30)
    at Module.m._compile (C:\data\devel\apps\sgte-it\coordinacion\juridicos\wspjn\node_modules\ts-node\src\index.ts:530:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:962:10)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] dev:ts-node: `ts-node -C ttypescript src/start.ts`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] dev:ts-node script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\sas\AppData\Roaming\npm-cache\_logs\2019-11-28T13_28_58_938Z-debug.log

This is the file app.ts

import express from 'express'
const app = express()   // Create a new express application instance
[...]

I'm using ttsc to run npm run prod and they work ok.

For the moment I'm keeping tsconfig-paths, but I'd like to get rid of it

thanks a lot

ttypescript does not look for typescript or transformers in expected places

I am attempting to run ttypescript with my company's build system, and we have a slightly nonstandard way of using node; we expect ttypescript to search NODE_PATH, like node does when it's set, to find transforms & for typescript; we also expect it to honor --preserve-symlinks.

I'm not totally sure why it's not working, but I noticed that ttypescript uses resolve(), and almost certainly uses different settings for it than what I'm invoking node with, which makes it not work. Depending on how I am running my ttypescript binary, either I'm getting it crashing trying to load the transformer, or when trying to load typescript.

Seems not working with ts-node

Hey there,

I'm trying to bootstrap a project with your tool, and i got an issue to make this "plugin" work with ts-node.

Here is a reproductible repository : https://github.com/DavidBabel/test

git clone [email protected]:DavidBabel/test.git
cd test
yarn install && yarn start

Here is the error :

/Users/david/dev-others/project-score/src/main/score.ts:1
(function (exports, require, module, __filename, __dirname) { export const scores = {
                                                              ^^^^^^

SyntaxError: Unexpected token export
    at new Script (vm.js:84:7)
    at createScript (vm.js:264:10)
    at Object.runInThisContext (vm.js:312:10)
    at Module._compile (internal/modules/cjs/loader.js:694:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:745:10)
    at Module.load (internal/modules/cjs/loader.js:626:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:566:12)
    at Function.Module._load (internal/modules/cjs/loader.js:558:3)
    at Module.require (internal/modules/cjs/loader.js:663:17)
    at require (internal/modules/cjs/helpers.js:20:18)

I do not know if it's related to https://github.com/cevek/ttypescript or the plugin https://github.com/grrowl/ts-transformer-imports

Fun part, it works well if i use ts-node-dev instead of ts-node.

parcel plugin not respecting "extends" keyword

I have tsconfig files in a folder tsconfig/. I added a toplevel tsconfig.json file with the contents

{
  "extends": "./tsconfig/tsconfig.json"
}

so my project directory looks like so:

src/
tsconfig/
  tsconfig.json
  tsconfig.declarations.json
tsconfig.json
package.json

I created this file specifically so this plugin can find my nested configs. Unfortunately it does not seem to notice the tsconfigs in the tsconfig/ folder. I know it does not because I have tried leaving an invalid json file in tsconfig/tsconfig.json and parcel still builds without issue. On a related note, if I could specify the location of my tsconfig file like I can with ttsc, I could avoid these extra steps.

Readme

Don't forget to exclude your transformers in the tsconfig.json

But this is dangerous advice, better to move in separate directory with own tsconfig
I have problem with Set iteration, because typescript make it as indexed for iteration

TypeScript 3.0 support?

I tried upgrading to typescript@rc and I'm getting this error with ttypescript 1.4.6 (works fine when just running tsc):

> ttsc
V:\ts-simple-ast\node_modules\typescript\lib\tsc.js:113686
})(ts || (ts = {}));
^

SyntaxError: Unexpected token }
    at Object.<anonymous> (C:\Users\david\AppData\Roaming\npm\node_modules\ttypescript\lib\tsc.js:26:14)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\Users\david\AppData\Roaming\npm\node_modules\ttypescript\bin\tsc:2:1)
    at Module._compile (module.js:652:30)

Any ideas? Sorry, I tried to look into it a bit but gave up.

-w (watch) flag throws a TypeError

I've tested this in v1.5.6 and v1.5.5. I run the ttsc transpiler via ttsc -w, and any code changes cause the transpiler to throw TypeError: Cannot read property 'text' of undefined. I've tested the same codebase with vanilla TypeScript and it transpiles without errors with the watch flag. Note that the code transpiles fine in the first run, it's the retranspilation that throw the error. Complete output below:

> ttsc -w
[3:28:09 PM] Starting compilation in watch mode...

[3:28:17 PM] Found 0 errors. Watching for file changes.
[3:28:20 PM] File change detected. Starting incremental compilation...

<project_dir_path>/node_modules/typescript/lib/typescript.js:89079
                throw e;
                ^

TypeError: Cannot read property 'text' of undefined
    at getErrorSpanForNode (<project_dir_path>/node_modules/typescript/lib/typescript.js:9187:40)
    at createDiagnosticForNodeInSourceFile (<project_dir_path>/node_modules/typescript/lib/typescript.js:9108:20)
    at Object.createDiagnosticForNode (<project_dir_path>/node_modules/typescript/lib/typescript.js:9099:16)
    at error (<project_dir_path>/node_modules/typescript/lib/typescript.js:31814:22)
    at resolveExternalModule (<project_dir_path>/node_modules/typescript/lib/typescript.js:33288:25)
    at resolveExternalModuleNameWorker (<project_dir_path>/node_modules/typescript/lib/typescript.js:33210:19)
    at resolveExternalModuleName (<project_dir_path>/node_modules/typescript/lib/typescript.js:33205:20)
    at checkImportDeclaration (<project_dir_path>/node_modules/typescript/lib/typescript.js:57055:49)
    at checkSourceElementWorker (<project_dir_path>/node_modules/typescript/lib/typescript.js:57412:28)
    at checkSourceElement (<project_dir_path>/node_modules/typescript/lib/typescript.js:57256:17)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! <project_name>@0.0.1 build:ts:dev: `ttsc -w`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the <project_name>@0.0.1 build:ts:dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     <user_dir_path>/.npm/_logs/2019-04-26T19_28_20_911Z-debug.log

Ability to suppress log?

Hey, awesome project! Can there be an option to disable the log in patch.js? I can't link to it because the source code on github doesn't seem up to date.

My reason:

image

missing import in published declaration file

lib/typescript.d.ts

/// <reference path="patchCreateProgram.d.ts" />
declare const TS: typeof ts;
export = TS;

Gives a compiler error Cannot find name 'ts'. and causes intellisense to not work.
Maybe you could use the newer declare const TS: import('typescript'); syntax added in [email protected]

TypeError: f is not a function

Hi, I made a transform for typescript and ttypescript is not working with it.

This is the transform, https://github.com/LeDDGroup/typescript-transform-jsx, and this are the test to show that the transform is working https://github.com/LeDDGroup/typescript-transform-jsx/blob/master/src/index.test.ts.

Here I'm testing it with ttypescript https://github.com/danielpa9708/test-typescript-transform-jsx. It throws this error:

$ npm run build

> [email protected] build /home/daniel/projects/mine/test-jsx
> ttsc

undefined:86983
                throw e;
                ^

TypeError: f is not a function
    at eval (eval at loadTypeScript (/home/daniel/projects/mine/test-jsx/node_modules/ttypescript/lib/loadTypescript.js:15:5), <anonymous>:1390:86)
    at reduceLeft (eval at loadTypeScript (/home/daniel/projects/mine/test-jsx/node_modules/ttypescript/lib/loadTypescript.js:15:5), <anonymous>:1102:30)
    at eval (eval at loadTypeScript (/home/daniel/projects/mine/test-jsx/node_modules/ttypescript/lib/loadTypescript.js:15:5), <anonymous>:1390:42)
    at transformRoot (eval at loadTypeScript (/home/daniel/projects/mine/test-jsx/node_modules/ttypescript/lib/loadTypescript.js:15:5), <anonymous>:81142:82)
    at Object.map (eval at loadTypeScript (/home/daniel/projects/mine/test-jsx/node_modules/ttypescript/lib/loadTypescript.js:15:5), <anonymous>:429:29)
    at Object.transformNodes (eval at loadTypeScript (/home/daniel/projects/mine/test-jsx/node_modules/ttypescript/lib/loadTypescript.js:15:5), <anonymous>:81129:30)
    at emitJsFileOrBundle (eval at loadTypeScript (/home/daniel/projects/mine/test-jsx/node_modules/ttypescript/lib/loadTypescript.js:15:5), <anonymous>:81485:32)
    at emitSourceFileOrBundle (eval at loadTypeScript (/home/daniel/projects/mine/test-jsx/node_modules/ttypescript/lib/loadTypescript.js:15:5), <anonymous>:81453:13)
    at forEachEmittedFile (eval at loadTypeScript (/home/daniel/projects/mine/test-jsx/node_modules/ttypescript/lib/loadTypescript.js:15:5), <anonymous>:81361:30)
    at Object.emitFiles (eval at loadTypeScript (/home/daniel/projects/mine/test-jsx/node_modules/ttypescript/lib/loadTypescript.js:15:5), <anonymous>:81442:9)

typescript version 3.1.6

Ability to run in old node environments

Could we change this library so it targets ES5 and not ESNext so that it could be used to build on old environments?

For example, my build machine uses an old version of nodejs that will checkout some typescript code, compile it, and run the tests, but this is broken now because a new version of ttypescript uses spread syntax (...).

Thanks!

require('ttypescript') alongside require('typescript')

Is it supported to programmatically use an unpatched typescript alongside the patched version from ttypescript? I see that if I require('ttypescript') then require('typescript') gets patched, whereas ideally ttypescript creates a separate instance of the compiler.

I think this would do the trick, but I'm not sure if you will accept a PR for it. Are there reasons to keep your current implementation?

"use strict";
import * as fs from 'fs';
import * as Path from 'path';
import {patchCreateProgram} from 'ttypescript/lib/patchCreateProgram';

// Create a new copy of the typescript library
function createTypescriptInstance() {
    const typescriptLibPath = require.resolve('typescript/lib/typescript');
    const typescriptLibSourceText = fs.readFileSync(typescriptLibPath, 'utf8');
    const __filename = typescriptLibPath;
    const __dirname = Path.dirname(__filename);
    const exports = {}, module = {exports};
    eval(typescriptLibSourceText);
    return module.exports as any;
}

module.exports = patchCreateProgram(createTypescriptInstance());

Run plugins before type check

I'm tying to run a transformer that replaces TypeNodes.

For example it may encounter an (undeclared) TypeNode named DataRecord and replace it with a TypeNode literal any.

The issue here is that apparently transformers are executed after typescript's type check, so by running ttsc i get error TS2304: Cannot find name 'DataRecord'. Same in vscode, even having correctly set the typescript.tsdk property to the ttypescript server path.

Is is possible to run transformers before typescript's type check or not?

Can i use more than one transform-plugin?

e.g.
typescript-transform-paths for resolving tsconfig > paths
and @zoltu/typescript-transformer-append-js-extension for preparing scripts for es6 browser loading

Can't get this to work with a simple example

I took this simple example from this blog post but I couldn't get it to run:

// transform.ts
import * as ts from 'typescript';

export default function(/*opts?: Opts*/) {
  const visitor: ts.Visitor = (node: ts.Node): ts.VisitResult => {
    if (ts.isCallExpression(node) && node.expression.getText(sf) == 'safely') {
      // we have found an expression of the form safely(...)
      // we can now replace or update it

      // get the argument to safely
      const target = node.arguments[0];
      // check to make sure it is a property access, like "a.b"
      if (ts.isPropertyAccessExpression(target)) {
        // return a binary expression with a && a.b
        return ts.createBinary(
          target.expression, // the left hand operand is the object
          ts.SyntaxKind.AmpersandAmpersandToken, // the && operator
          target,
        ); // the right hand operand is the full expression
      }
    }
    // otherwise continue visiting all the nodes
    return ts.visitEachChild(node, visitor, ctx);
  };
  return (ctx: ts.TransformationContext): ts.Transformer => {
    return (sf: ts.SourceFile) => ts.visitNode(sf, visitor(ctx, sf));
  };
}
// example.ts
const a = {b: 1}
const c = safely(a.b)

tsconfig.json

{
  "compilerOptions": {
   "customTransformers": {
      "before": [
        "./transform.ts"
      ]
    }
  }
}

I ran:

ttsc example.ts

Result:

var a = { b: 1 };
var c = safely(a.b);

Expected:

var a = { b: 1 };
var c = a && a.b;

Git URL is invalid

I just wanted to let you know that the Git URL for ttypescript is invalid. Not really that big of a deal; still easy enough to find your repo. I just keep running into it, because I wind up using npm info to open it. Doing the search on Github pops it right up, or can erase most of the url (back to the parent repository) after navigating to the broken link. I just prefer launching a URL straight from the command line if I can, and having that link in the npm info is rather useful. ๐Ÿ™‚

Publish 1.5.7

Would it be possible to release a 1.5.7 with the fixes on master? The new package.json with typescript listed in peerDependencies is a fix for a blocker to using yarn v2 (pnp).

Expose program to custom transformers

If custom transformers had access to the current Program, they would be able to use its TypeChecker to introspect on the types in the code being transformed. CustomTransformers with knowledge of the type system could have lots of interesting uses; e.g. using a specific decorator to mark blocks of code to be transformed, or auto-generating type guards from interfaces.

Feature Request: Allow the export of the program instead of the transformer

I would really love to use ttypescript

But I'm using the awesome ts-simple-ast library to create a transformer and it creates the program for you. So you never in control of this code:

export default function (program: ts.Program, pluginOptions: {}) {
    return (ctx: ts.TransformationContext) => {
        return (sourceFile: ts.SourceFile) => {
            return sourceFile;
        }
    }
}

So if you could do something like.

export default function() : ts.Program {
      const program: ts.Program = doTsSimpleJsStuff();
      return program
}

that would work.

I believe putting a signature check somewhere here would do the trick but the module resolution should happen earlier than here.

Is `ts-node` a required dependency to use this module?

Up until 1.5.6, I was able to use ttypescript without installing ts-node as a separate dependency. However, from 1.5.7 onwards, the ttsc command fails when ts-node is not installed.

I do see a commit that moves ts-node from dependencies list to peerDependencies list, but I am not sure why ts-node is required when I just want to compile the code using ttsc

Custom transformers discarded if some are given as arguments, expected behavior?

Not sure if this is the expected behavior or not, but it does not sounds right anyway:

If the emit() method is given some customTransformers, the ones ttypescript would normally used from plugins are totally discarded.

Discarded at line 77 there:

program.emit = function newEmit(
targetSourceFile?: ts.SourceFile,
writeFile?: ts.WriteFileCallback,
cancellationToken?: ts.CancellationToken,
emitOnlyDtsFiles?: boolean,
customTransformers: ts.CustomTransformers = pluginCreator.createTransformers({ program })
): ts.EmitResult {
return originEmit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
};

ESLint 6 Compatibility

Environment

  • ESLint version: 6.1.0
  • ttypescript: 1.5.7

Upgrading to ESLint v6 shows warnings when installing:
npm WARN [email protected] requires a peer of ts-node@^8.0.2 but none is installed. You must install peer dependencies yourself.

Typescript transform paths deleting / not generating import in *.d.ts files?

Hi,

I'm looking into how to go about fixing this bug:
LeDDGroup/typescript-transform-paths#24

Import declarations are being left off generated *.d.ts files. Looking through the source code I think this is the relevant section that does the work, but I don't see why it would cause the import to be left off, so I was wondering if maybe you would have any additional pointers for me:

  function visit(node: ts.Node): ts.VisitResult<ts.Node> {
    if (
      resolver &&
      ts.isExportDeclaration(node) &&
      !node.exportClause &&
      !compilerOptions.isolatedModules &&
      !resolver.moduleExportsSomeValue(node.moduleSpecifier)
    ) {
      return undefined;
    }
    if (ts.isImportDeclaration(node)) {
      return unpathImportDeclaration(node);
    }
    if (ts.isExportDeclaration(node)) {
      return unpathExportDeclaration(node);
    }

    return ts.visitEachChild(node, visit, context);
  }

The above snippet is taken from this source file:

https://github.com/LeDDGroup/typescript-transform-paths/blob/master/src/index.ts

Thoughts?

TIA,
Ole

P.S. Also asked for help on SO

Does not work with rollup

Im trying to use plugin @zerollup/ts-transform-paths, it works when using ttsc but does not work with rollup

Rollup config

import tsPlugin from 'rollup-plugin-typescript2';
import ttypescript from 'ttypescript'
import pkg from './package.json';

export default {
  input: './index.ts',
  output: [
    {
      file: pkg.main,
      format: 'cjs'
    },
    {
      file: pkg.module,
      format: 'es'
    }
  ],
  external: [
    ...Object.keys(pkg.dependencies || {}),
    ...Object.keys(pkg.peerDependencies || {})
  ],
  plugins: [
    tsPlugin({
      tsconfig: 'tsconfig.build.json',
      typescript: ttypescript
    })
  ]
};

tsconfig compiler options:

{
    "baseUrl": ".",
    "paths": {
      "client/*": ["./*"]
    },
    "plugins": [{ "transform": "@zerollup/ts-transform-paths" }]
}

When compling with ttsc it replaces paths starting with client as expected, but does nothing when building with rollup.

Im using

    "typescript": "3.1.6",
    "ttypescript": "^1.5.5",
    "@zerollup/ts-transform-paths": "1.6.5"
    "rollup": "0.68.2",
    "rollup-plugin-typescript2": "0.18.1",

ttsc missing compilerOptions

Try to use ttypescript, but get error:
> rimraf es | ttsc -p tsconfig.json
[node_modules]\ttypescript\lib\patchCreateProgram.js:38
if (compilerOptions.configFilePath === undefined) {

According to error it's seems problem with compilerOptions
TypeError: Cannot read property 'configFilePath' of undefined

Issue reproducible with [email protected] (Older 2.8 works ok)

Do not register ts-node-config/tsconfig.json in all circumstances?

Hey, I was trying to get this to work with istanbul (nyc), mocha, and ts-node. This is my setup (setup is from here):

// package.json under "scripts"
"test": "cross-env TS_NODE_COMPILER=\"ttypescript\" nyc --reporter=lcov mocha --opts mocha.opts",

// mocha.opts
--require ts-node/register
--recursive
--reporter progress
src/tests/**/*.ts

Which gives the following error:

V:\test-project\node_modules\ts-node\src\index.ts:209
  const readFile = options.readFile || ts.sys.readFile
                                              ^
TypeError: Cannot read property 'readFile' of undefined
    at Object.register (V:\test-project\node_modules\ts-node\src\index.ts:209:47)
    at Object.<anonymous> (V:\test-project\node_modules\ttypescript\lib\patch.js:5:20)
    at Module._compile (module.js:652:30)
    at Module.replacementCompile (V:\test-project\node_modules\nyc\node_modules\append-transform\index.js:58:13)
    at module.exports (V:\test-project\node_modules\nyc\node_modules\default-require-extensions\js.js:8:9)
   ...etc...

I took a look at the line where there's the error and added two console.log statements before:

// node_modules/ts-node/dist/index.js
var ts = require(compiler);
var transformers = options.transformers || undefined;
console.log(compiler); // outputs: "ttypescript"
console.log(ts); // outputs: {}
var readFile = options.readFile || ts.sys.readFile;

Then looked further into ttypescript/lib/typescript.js and found it was requiring patch.js. Then in patch.js I found the following:

// node_modules/ttypescript/lib/patch.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = require("path");
const customRequire_1 = require("./customRequire");
console.log("1"); // happens
require('ts-node').register({ project: __dirname + '/../ts-node-config/tsconfig.json' });
console.log("2"); // doesn't happen

Finally, by commenting out the register line everything was working perfectly and my tests ran:

// node_modules/ttypescript/lib/patch.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = require("path");
const customRequire_1 = require("./customRequire");
// require('ts-node').register({ project: __dirname + '/../ts-node-config/tsconfig.json' });

What does this register do? Is it necessary all the time? Is there a way we can change the code here to prevent the error in this circumstance? Thanks!

declarations error

I have
node_modules/ttypescript/lib/typescript.d.ts:2:15 - error TS2502: 'ts' is referenced directly or indirectly in its own type annotation. 2 declare const ts: typeof ts;
when importing 'ttypescript'.
Looks like declarations are incorrect.

Move typescript to peer dependency?

Hey, when having a typescript dependency of ^3.0.1 and installing the packages with yarn, it will create a node_modules/ttypescript/node_modules/typescript package with a < 3.0 version. This will cause all the source files to be parsed with TS 2.9, which lead to a lot of confusion for me hah. It's a problem because the SyntaxKind numbers have changed so the following happens:

function visitSourceFile(sourceFile, context) {
    console.log(ts.version); // 3.0.1
    console.log(ts.SyntaxKind[sourceFile.kind]); // PropertyAssignment, sourceFile was created with 2.9
    // etc...
}

I found that replacing the node_modules/ttypescript/node_modules/typescript folder with a 3.0 version or installing via npm solves the issue.

To fix this, would it be possible to change typescript to be a peer dependency? Or is there a better solution?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.