GithubHelp home page GithubHelp logo

duffman / tspath Goto Github PK

View Code? Open in Web Editor NEW
153.0 4.0 33.0 199 KB

TypeScript path alias resolver

License: GNU Lesser General Public License v2.1

TypeScript 90.78% JavaScript 9.22%
typescript path utility nodejs npm-module

tspath's Introduction

TSPath

TypeScript Path Alias Resolver

Important update

The issues with the basePath relative to the outDir have now been corrected... until someone says something else ;)

So what is it?

Everyone working in a TypeScript project that grows beyond a certains limit will eventually experience the situation commonly described as path hell, the snippet below is an example of such hell.

Path hell
 import { IgniterApplication } from "../../../Application/IgniterApplication";
 import { CrcCalculator }      from "../../../../../../../Utilities/FileUtilities";
 import { IMessageHandler }    from "../../../../Messaging/IMessageHandler";
 import { IMessageHub }        from "../../../../Messaging/Hub/IMessageHub";
 import { CronTabHelper }      from "../../../../../../../Utilities/CronTabHelper";
 import { GLog }               from "../../../Application/GLog";

Configuration

By specifying path aliases in tsconfig.json you can use that alias to form an "absolute path"

{
  "compilerOptions": {
    ...
    "paths": {
      "@App/*":         ["./Application/*"],
      "@Messaging/*":   ["./Messaging/*"],
      "@Utils/*":       ["./Server/Tools/Utilities/*"]
    }
  }
}

For full compability with the internal JavaScript parser,
specify es5 as target.

{
  "compilerOptions": {
    "target": "es5"
     ...
    }
}

Below is the sample example but with Path Aliases instead of relative paths added, as you can see, the readability have improved significantly!

 import { IgniterApplication } from "@App/IgniterApplication";
 import { CrcCalculator }      from "@Utils/FileUtilities";
 import { IMessageHandler }    from "@Messaging/IMessageHandler";
 import { IMessageHub }        from "@Messaging/Hub/IMessageHub";
 import { CronTabHelper }      from "@Utils/CronTabHelper";
 import { GLog }               from "@App/GLog";

The TypeScript compiler will be able to resolve the paths so this will compile without problems, however the JavaScript output will not be possible to execute by Node nor a Web Browser, why? the reason is simple!

The JavaScript engine does not know anything about the compile time TypeScript configuration.

In order to run your JavaScript code, the path aliases now needs to be made into relative paths again, here is when Const comes into play.

So, simply run:

$ tspath

Yes, that´s it, really!

Running headless, slip in a -f in order to bypass the confirmation prompt.

$ tspath -f

Say bye bye to the relative path hell!

<<<<<<< HEAD

Const

TypeScript Path Alias Resolver


⚠️ Important! There have been reports of shaky behaviour when tspath is run with node 9.x, I am looking into the issue, if one of you who reported it happened to see where the problem occurs, please share :)


Everyone working in a TypeScript project that grows beyond a certains limit will eventually experience the situation commonly described as path hell, the snippet below is an example of such hell.

Path hell
 import { IgniterApplication } from "../../../Application/IgniterApplication";
 import { CrcCalculator }      from "../../../../../../../Utilities/FileUtilities";
 import { IMessageHandler }    from "../../../../Messaging/IMessageHandler";
 import { IMessageHub }        from "../../../../Messaging/Hub/IMessageHub";
 import { CronTabHelper }      from "../../../../../../../Utilities/CronTabHelper";
 import { GLog }               from "../../../Application/GLog";

By specifying path aliases in tsconfig.json you can use that alias to form an "absolute path"

{
  "compilerOptions": {
    ...
    "paths": {
      "@App/*":         ["./Application/*"],
      "@Messaging/*":   ["./Messaging/*"],
      "@Utils/*":       ["./Server/Tools/Utilities/*"]
    }
  }
}

Below is the sample example but with Path Aliases instead of relative paths added, as you can see, the readability have improved significantly!

 import { IgniterApplication } from "@App/IgniterApplication";
 import { CrcCalculator }      from "@Utilils/FileUtilities";
 import { IMessageHandler }    from "@Messaging/IMessageHandler";
 import { IMessageHub }        from "@Messaging/Hub/IMessageHub";
 import { CronTabHelper }      from "@Utils/CronTabHelper";
 import { GLog }               from "@App/GLog";

The TypeScript compiler will be able to resolve the paths so this will compile without problems, however the JavaScript output will not be possible to execute by Node nor a Web Browser, why? the reason is simple!

The JavaScript engine does not know anything about the compile time TypeScript configuration.

In order to run your JavaScript code, the path aliases now needs to be made into relative paths again, here is when Const comes into play.

So, simply run:

$ tspath

Yes, that´s it, really!

Options

Arg Type Description Default
-f boolean optional - skip the confirmation prompt displayed before tspath parses the project (e.g. tspath -f) false
-c boolean optional - do not include superfluous whitespace characters and line terminators (e.g. tspath -c) false

Skipping files

To skip any file in your project, include the following comment anywhere in the file to skip:

// tspath:skip-file

Say bye bye to the relative path hell!

Options

Arg Type Description Default
-f boolean optional - skip the confirmation prompt displayed before tspath parses the project (e.g. tspath -f) false

7b5420c0b1b2d142628c0ebc5192ad8edaf107bf

tspath's People

Contributors

cinjoff avatar coldmindsoft avatar duffman avatar mattroberts297 avatar odudek 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

tspath's Issues

Error when used in CI/CD

When running tspath in a CI/CD script, I have the following error:

npx tspath -f -s
TSPath v2.6.8
Try: 'tspath --help' for more information
Parsing project: my-project /opt/gitlab-runner/builds/xxx/yyy/packages/my-project/
Indexing files...
/opt/gitlab-runner/builds/xxx/yyy/node_modules/tspath/utils/utils.js:64
process.stdout.clearLine();
^
TypeError: process.stdout.clearLine is not a function
at Function.updateLine (/opt/gitlab-runner/builds/xxx/yyy/node_modules/tspath/utils/utils.js:64:24)
at ParserEngine.walkSync (/opt/gitlab-runner/builds/xxx/yyy/node_modules/tspath/parser-engine.js:438:31)
at ParserEngine.walkSync (/opt/gitlab-runner/builds/xxx/yyy/node_modules/tspath/parser-engine.js:435:33)
at ParserEngine.walkSync (/opt/gitlab-runner/builds/xxx/yyy/node_modules/tspath/parser-engine.js:435:33)
at ParserEngine. (/opt/gitlab-runner/builds/xxx/yyy/node_modules/tspath/parser-engine.js:148:18)
at Generator.next ()
at /opt/gitlab-runner/builds/xxx/yyy/node_modules/tspath/parser-engine.js:31:71
at new Promise ()
at __awaiter (/opt/gitlab-runner/builds/xxx/yyy/node_modules/tspath/parser-engine.js:27:12)
at ParserEngine.execute (/opt/gitlab-runner/builds/xxx/yyy/node_modules/tspath/parser-engine.js:112:16)

I can reproduce the same error local using the following command:
npx tspath -f -s > debug.log

I don't see any difference on console output when using -s parameter.

Any idea?

Thanks for your support

outDir should be independent of baseUrl

Consider the following tsconfig.json.

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es2016",
        "outDir": "./dist",
        "baseUrl": "./src",
        "paths": {
            "core/*": ["core/*"]
        }
    },
    "exclude": [
        "node_modules",
        "dist"
    ]
}

outDir should be independent of baseUrl, so that resulting output directory is projectRoot/dist, not projectRoot/src/dist.

AFAIK, current implementation searchs for projectRoot/src/dist and throw errors.

Mixed output slashes - Cannot find module './src\util\getSomething'

Please advise if doing this right?

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "./",
    "allowJs": false,
    "strict": true,
    "target": "es6",
    "module": "commonjs",
    "lib": ["dom", "es6", "es5", "es2017", "esnext.asynciterable"],
    "sourceMap": true,
    "moduleResolution": "node",
    "paths": {
      "src/*": ["src/*"]
    },
    "declaration": true,
    "rootDir": "./src",
    "outDir": "dist"
  },
  "exclude": ["dist"],
  "include": [ "src"]
}

Original Folder structure

src /
  util/
    getSomething.ts
  index.ts

Output Folder structure

dist /
  util/
    getSomething.js
  index.js

index.ts

import getSomething from 'src/util/getSomething';

package.json script

{
"build": "tsc && tspath -f",
"start": "node dist/index.js"
}

The build works but when I run start I get error.

Note: I am using windows.

npm start

Error: Cannot find module './src\util\getSomething'
Require stack:
c:\apps\example-typescript-node\dist\index.js

Map directly to a file?

I'm trying to do the following, but it does not seem to work:

    "paths": {
      "leaflet": ["./node_modules/leaflet/dist/leaflet.js"]
    }

The leaflet package does not use a minified file as its entry point. I use the standard

import 'leaflet' vs import 'leaflet/dist/leaflet.js'

in my typescript files so I can still get type support.

I have a separate tsconfig.prod.json with the above definition so that on build, it can remap leaflet references to that.

Is there a way to do this kind of mapping?

TypeError: chalk.red.bold is not a function

Description

C:\Users\Dief\Documents\Source\GLFW\rewrite-test\node_modules\tspath\parser-engine.js:331
                log(chalk.red.bold("Missing required field:") + " \"" + chalk.bold.underline(key) + "\"");
                              ^

TypeError: chalk.red.bold is not a function

Notes
Chalk version installed is currently 2.4.2, however I've also manually installed chalk 2.3.0 to match what's in package.json. Same error for both.

TypeError: Cannot read property 'type' of undefined

This appears when I run tspath -f (or tspath):

/home/sandor/.nvm/versions/node/v8.10.0/lib/node_modules/tspath/node_modules/escodegen/escodegen.js:2446
        type = expr.type || Syntax.Property;
                    ^

TypeError: Cannot read property 'type' of undefined
    at CodeGenerator.generateExpression (/home/sandor/.nvm/versions/node/v8.10.0/lib/node_modules/tspath/node_modules/escodegen/escodegen.js:2446:21)
    at CodeGenerator.CallExpression (/home/sandor/.nvm/versions/node/v8.10.0/lib/node_modules/tspath/node_modules/escodegen/escodegen.js:1870:34)
    at CodeGenerator.generateExpression (/home/sandor/.nvm/versions/node/v8.10.0/lib/node_modules/tspath/node_modules/escodegen/escodegen.js:2452:28)
    at CodeGenerator.VariableDeclarator (/home/sandor/.nvm/versions/node/v8.10.0/lib/node_modules/tspath/node_modules/escodegen/escodegen.js:1436:26)
    at CodeGenerator.generateStatement (/home/sandor/.nvm/versions/node/v8.10.0/lib/node_modules/tspath/node_modules/escodegen/escodegen.js:2465:33)
    at block (/home/sandor/.nvm/versions/node/v8.10.0/lib/node_modules/tspath/node_modules/escodegen/escodegen.js:1459:38)
    at CodeGenerator.VariableDeclaration (/home/sandor/.nvm/versions/node/v8.10.0/lib/node_modules/tspath/node_modules/escodegen/escodegen.js:1477:17)
    at CodeGenerator.generateStatement (/home/sandor/.nvm/versions/node/v8.10.0/lib/node_modules/tspath/node_modules/escodegen/escodegen.js:2465:33)
    at CodeGenerator.Program (/home/sandor/.nvm/versions/node/v8.10.0/lib/node_modules/tspath/node_modules/escodegen/escodegen.js:1707:43)
    at CodeGenerator.generateStatement (/home/sandor/.nvm/versions/node/v8.10.0/lib/node_modules/tspath/node_modules/escodegen/escodegen.js:2465:33)

Retain line breaks

After running tspath line breaks are stripped from the file and all code is on one line only. Would it be possible to retain them?

sourceMap support

Hello,

Seems like tspath makes slight modifications in the generated code and that breaks the compability with the previously generated source maps.

Is there a way to only modify the require and imports and not to touch the rest. Would that work?

tspath works incorrect

tspath doesn't work correctly on latest versions of ts

Here is my stackoverflow question which describes the core of the problem

ts version is 4.5.5

If the problems are really only on my side, then please help solve the problem, otherwise it seems to me that I should either update or publish in the readme that the project is dead

Support '#!/usr/bin/env ts-node' scripts

Hello. I like being able to run my scripts locally, they usually have a little short main() function they run if they are run directly.

At the moment, if I create a short script & run tspath -f throws, tspath seems to not be able to work with it:

TSPath 1.3.7
Parsing project: take-over-the-world /iamgroot/src/take-over-the-world/
Unable to parse file: /iamgroot/src/take-over-the-world/dist/config.js
Error: Error: Line 1: Unexpected token ILLEGAL
    at ErrorHandler.constructError (/iamgroot/src/take-over-the-world/node_modules/esprima/dist/esprima.js:5012:22)
    at ErrorHandler.createError (/iamgroot/src/take-over-the-world/node_modules/esprima/dist/esprima.js:5028:27)
    at ErrorHandler.throwError (/iamgroot/src/take-over-the-world/node_modules/esprima/dist/esprima.js:5035:21)
    at Scanner.throwUnexpectedToken (/iamgroot/src/take-over-the-world/node_modules/esprima/dist/esprima.js:5164:35)
    at Scanner.scanPunctuator (/iamgroot/src/take-over-the-world/node_modules/esprima/dist/esprima.js:5667:19)
    at Scanner.lex (/iamgroot/src/take-over-the-world/node_modules/esprima/dist/esprima.js:6264:22)
    at Parser.nextToken (/iamgroot/src/take-over-the-world/node_modules/esprima/dist/esprima.js:2079:34)
    at new Parser (/iamgroot/src/take-over-the-world/node_modules/esprima/dist/esprima.js:1916:15)
    at Object.parse (/iamgroot/src/take-over-the-world/node_modules/esprima/dist/esprima.js:120:19)
    at ParserEngine.processFile (/iamgroot/src/take-over-the-world/node_modules/tspath/src/parser-engine.js:170:27) {
  index: 0,
  lineNumber: 1,
  description: 'Unexpected token ILLEGAL'
}

Example dist/config.js:

#!/usr/bin/env ts-node
console.log("hi!")

Some general description of using ts-node to make scripts directly runnable, the technique i'm trying to use, is in this great write-up: Shelling with TypeScript.

SyntaxError: Unexpected token } in JSON at position 381

Hi, I'm getting this error:

$  npx tspath
TSPath 1.3.7
? Process project at: </Users/jplew/Sites/mysite/ops/apps/api/> ? true
undefined:20
}
^

SyntaxError: Unexpected token } in JSON at position 381
    at JSON.parse (<anonymous>)
    at ParserEngine.readConfig (/Users/jplew/Sites/mysite/ops/apps/api/node_modules/tspath/src/parser-engine.js:213:30)
    at ParserEngine.execute (/Users/jplew/Sites/mysite/ops/apps/api/node_modules/tspath/src/parser-engine.js:90:36)
    at TSPath.processPath (/Users/jplew/Sites/mysite/ops/apps/api/node_modules/tspath/src/tspath.js:39:25)
    at Confirm.callback (/Users/jplew/Sites/mysite/ops/apps/api/node_modules/tspath/src/tspath.js:29:27)
    at Confirm.<anonymous> (/Users/jplew/Sites/mysite/ops/apps/api/node_modules/prompt-base/index.js:625:10)
    at runCallback (timers.js:810:20)
    at tryOnImmediate (timers.js:768:5)
    at processImmediate [as _immediateCallback] (timers.js:745:5)

My tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "moduleResolution": "node",
    "module": "commonjs",
    "sourceMap": true,
    "rootDir": "src",
    "outDir": "dist",
    "lib": [
      "esnext", "dom"
    ],
    "baseUrl": "./src",
    "paths": {
      "@root/*": ["./*"],
      "@resolvers/*": ["resolvers/*"]
    }
  },
  "include": ["src"],
  "exclude": ["src/generated"],
}

My project structure:
image

I also added this to my package.json:

  "_moduleAliases": {
    "@root": "./dist",
    "@resolvers": "./dist/resolvers"
  }

Node version: 8.11.2

Any ideas?

Error: Line 2: Unexpected token

The line cited is

import _camelCase from '@lodash/camelCase';

I'm not seeing any invalid syntax there, and there is no other information (besides a stacktrace within tspath).

Minor bug: Dependency name mistaken as a path

There is a dependency named graphql in node_modules.
I also have a src/graphql folder in my project.
In this folder, I have a Typescript file that imports from the graphql dependency:

import { GraphQLError } from 'graphql';

This is mistaken as a path reference by tspath, and it gets transpiled as:

const graphql_1 = require("../graphql/index.js");

Of course, the line can be skipped with // tspath: skip-file but it would be nice if tspath recognized that this is a reference to a dependency, and not to a folder. It would be as simple as collecting node_modules subfolders and giving them precedence over folder names.

JS paths not being replaced

Same as #4

tsconfig.json

{
	"compilerOptions": {
		"incremental": true, // Enable incremental compilation
		"composite": false, // Enable constraints that allow a TypeScript project to be used with project references. (enable for declaration files)
		"tsBuildInfoFile": "logs/.tsbuildinfo", // Specify the folder for .tsbuildinfo incremental compilation files.
		"target": "es6", // Set the JavaScript language version for emitted JavaScript and include compatible library declarations.
		"lib": [ // Specify a set of bundled library declaration files that describe the target runtime environment.
			"ESNext",
			"ESNext.Array",
			"ESNext.AsyncIterable",
			"ESNext.Intl",
			"ESNext.Symbol"
		],
		"experimentalDecorators": true, // Enable experimental support for TC39 stage 2 draft decorators.
		"emitDecoratorMetadata": true, // Emit design-type metadata for decorated declarations in source files.
		"module": "CommonJS", // Specify what module code is generated.
		"rootDir": "src", // Specify the root folder within your source files.
		"moduleResolution": "node", // Specify how TypeScript looks up a file from a given module specifier.
		"baseUrl": ".", // Specify the base directory to resolve non-relative module names.
		"paths": {
			"@lib/*": [
				"./src/lib/*"
			],
			"@scripts/*": [
				"./src/scripts/*"
			],
			"@typings/*": [
				"./src/typings/*"
			],
			"@core/*": [
				"./src/*"
			],
			"@commands/*": [
				"./src/commands/*"
			],
			"@subcommands/*": [
				"./src/commands/subcommands/*"
			],
			"@listeners/*": [
				"./src/listeners"
			]
		}, // A series of entries which re-map imports to lookup locations relative to the baseUrl.
		"typeRoots": [ // Specify multiple folders that act like ./node_modules/@types.
			"node_modules/@types"
		],
		"allowUmdGlobalAccess": true, // Allow accessing UMD globals from modules.
		"resolveJsonModule": true, // Enable importing .json files
		"noResolve": false, // Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project.
		"allowJs": false, // Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files.
		"checkJs": false, // Enable error reporting in type-checked JavaScript files.
		"declaration": false, // Generate .d.ts files from TypeScript and JavaScript files in your project.
		"declarationMap": false, // Create sourcemaps for d.ts files.
		"emitDeclarationOnly": false, // Only output d.ts files and not JavaScript files.
		"sourceMap": false, // Create source map files for emitted JavaScript files.
		"outDir": "build", // Specify an output folder for all emitted files.
		"esModuleInterop": true, // Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility.
		"forceConsistentCasingInFileNames": true, // Ensure that casing is correct in imports.
		"strict": true, // Enable all strict type-checking options.
		"noImplicitAny": false, // Enable error reporting for expressions and declarations with an implied `any` type.
		"strictNullChecks": true, // When type checking, take into account `null` and `undefined`.
		"strictFunctionTypes": true, // When assigning functions, check to ensure parameters and the return values are subtype-compatible.
		"strictBindCallApply": true, // Check that the arguments for `bind`, `call`, and `apply` methods match the original function.
		"strictPropertyInitialization": false, // Check for class properties that are declared but not set in the constructor.
		"noImplicitThis": true, // Enable error reporting when `this` is given the type `any`.
		"useUnknownInCatchVariables": false, // Type catch clause variables as 'unknown' instead of 'any'.
		"alwaysStrict": true, // Ensure 'use strict' is always emitted.
		"allowUnusedLabels": true, // Disable error reporting for unused labels.
		"allowUnreachableCode": false, // Disable error reporting for unreachable code.
		"skipLibCheck": true // Skip type checking all .d.ts files.
	},
	"include": [
		"src"
	],
	"exclude": [
		"build",
		"node_modules",
		"**/*.js"
	]
}

Project folder structure
image

src/index.ts imports

import { AstraniumClient } from "@lib/Client";
import type { Guild } from "discord.js";
import { Logger } from "@lib/Logger";
import { PrismaClient } from "@prisma/client";

build/index.js imports

const Client_1 = require("@lib/Client");
const Logger_1 = require("@lib/Logger");
const client_1 = require("@prisma/client");

Running npx tspath -f and getting the following:

TSPath v2.6.8
Try: 'tspath --help' for more information
Parsing project: astranium C:\Users\ascen\OneDrive\Documents\Programming\Bots\Astranium\
Indexing files...
Total files processed: 50
Total paths processed: 77
Operation finished in: 537.403ms
Project is prepared, now run it normally!

Node version: v17.2.0
TypeScript version: v4.8.4
tspath version: v2.6.8

Unable to parse file: 'Unexpected token ...'

I am getting the following error:

Unable to parse file: /path/to/file 
Error: Error: Line XX: Unexpected token ...
...
description: 'Unexpected token ...'

My tsconfig.json:

{
	"compilerOptions": {
		"alwaysStrict": true,
		"allowJs": true,
		"baseUrl": ".",
		"declaration": true,
		"esModuleInterop": true,
		"experimentalDecorators": true,
		"lib": [
			"ESNext",
			"ESNext.AsyncIterable",
			"DOM"
		],
		"module": "commonjs",
		"moduleResolution": "node",
		"noFallthroughCasesInSwitch": true,
		"noImplicitThis": true,
		"noImplicitAny": true,
		"noUnusedLocals": true,
		"noUnusedParameters": true,
		"outDir": "./dist",
		"rootDir": "./",
		"paths": {
			"~/*": [
				"./*"
			],
			"@/*": [
				"./*"
			]
		},
		"sourceMap": true,
		"strict": true,
		"strictNullChecks": true,
		"strictFunctionTypes": true,
		"strictPropertyInitialization": true,
		"target": "ES2018",
	},
	"include": [
		"src/**/*"
	],
	"exclude": [
		"node_modules"
	]
}

My only .ts file in /src

// /src/index.ts
const myarr:string[] = [];

const a = {
	...myarr
}

Step to reproduce:

tsc -b
npx tspath -f
// Typescript version
Version 4.3.2

Why the pareser is not understanfing the syntax "..."? Is there any configuration I am missing?

High vulnerability from set-value

Hi, running npm audit reveals a Prototype Pollution vulnerability in this package, coming from set-value.

Are you open to contributions to fix this?

How do I install and run this please?

I really want to get this working. The only instruction in the read me is to simply run $ tspath. NPM packages are not directly runnable? This is a bash prompt. Is it because I'm on windows? Do I install as a dev dependency? What then? This may sound ridiculously naive. Could the readme please be more explicit? I'm on an electron project under windows.

Doesn't work, false possitive

Hello, I was trying to use it on simple test project. My structure is:

  • server
  • libs
    • models
  • tsconfig.json

tsconfig.json looks like that:

{
  "compilerOptions": {
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es6", "dom"],
    "mapRoot": "./dist",
    "module": "commonjs",
    "moduleResolution": "node",
    "outDir": "./dist",
    "sourceMap": true,
    "target": "es6",
    "typeRoots": [
      "node_modules/@types"
    ],
    "baseUrl": ".",
    "paths": {
      "~/*": ["libs/*"]
    }
  }
}

After executing tspath I get this message:

Total files processed: 5
Total paths processed: 2
Operation finished in: 22.956ms
Project is prepared, now run it normally!

However paths were not replaced. Files were altered but paths remain the same. What do I do wrong?

--filter and --force don't work

When running tspath --force it still prompts the user. However, if I run tspath -f it doesn't.

Likewise, when I run tspath --filter="rr" it ignores the filter and still processes .js files. This is important because, by default tspath isn't processing the d.ts files.

Lastly, I noticed the version on NPM is 1.3.7 but github shows 1.3.5. Not sure how this is the case. When I pull down 1.3.5 from github it appears to work correctly with --force and --filter. However, 1.3.7 installed via NPM displays the issues I noted above.

execute after tsc build

Maybe not directly an issue in this repo, but I think related. Is it possible to run tspath after each build when running tsc -w?

Not reading output file directly

tucker@GLaDOS:/mnt/e/Webdesign/salted-vagrant/rest-hooks$ npx tspath
TSPath 1.3.7
? Process project at: </mnt/e/Webdesign/salted-vagrant/rest-hooks/> ? true
Parsing project: rest-hooks /mnt/e/Webdesign/salted-vagrant/rest-hooks/
fs.js:119
    throw err;
    ^

Error: ENOENT: no such file or directory, scandir '/mnt/e/Webdesign/salted-vagrant/rest-hooks/src/lib'
    at Object.readdirSync (fs.js:806:3)
    at ParserEngine.walkSync (/mnt/e/Webdesign/salted-vagrant/rest-hooks/node_modules/tspath/src/parser-engine.js:260:24)
    at ParserEngine.execute (/mnt/e/Webdesign/salted-vagrant/rest-hooks/node_modules/tspath/src/parser-engine.js:101:14)
    at TSPath.processPath (/mnt/e/Webdesign/salted-vagrant/rest-hooks/node_modules/tspath/src/tspath.js:39:25)
    at Confirm.callback (/mnt/e/Webdesign/salted-vagrant/rest-hooks/node_modules/tspath/src/tspath.js:29:27)
    at Confirm.<anonymous> (/mnt/e/Webdesign/salted-vagrant/rest-hooks/node_modules/prompt-base/index.js:625:10)
    at processImmediate (timers.js:637:19)

Usually I build via tsc --emitDeclarationOnly -p ./src. This outputs ambient declarations to the lib folder. But for some reason tspath is try to go to src/lib instead.

tsconfig.json

{
  "compilerOptions": {
    /* Basic Options */
    "target": "esnext",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    "jsx": "react",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    "declaration": true,                      /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    "outDir": "lib",                         /* Redirect output structure to the directory. */
    "rootDir": "./src",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    "baseUrl": "./src",                       /* Base directory to resolve non-absolute module names. */
    "paths": {"~/*": ["*"]},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": ["./src"],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    "allowSyntheticDefaultImports": true,     /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    "emitDecoratorMetadata": true         /* Enables experimental support for emitting type metadata for decorators. */
  },
  "exclude": [
    "node_modules"
  ]
}

Changes functionality with string templates containing new lines

When trying to add this to one of our projects, I noticed the library changing the behavior of several of our classes that format strings. Digging into the output code, it appears that tspath is adding a semicolon immediately after return when returning a string template, so, return ` would become return;` . I created a test case to replicate the behavior.

Source:

class TestClass {

        public getString(): string {
                const content = `
                        Do something
                `;
                this._notUsed(content);
                return this._getString(content);
        }

        private _notUsed(value: string): string {
                return `
                        ${value}
               `;

        }

        private _getString(value: string): string {
                return `
                        This ${value} is on the next line
                `;
        }
}

console.log(new TestClass().getString());

Expected:


                        This 
                        Do something
                 is on the next line

Returned:
undefined

Reworked your package

Hey Duffman,
I wanted you to know that I love your package and wanted to use it for AWS SAM.
Sadly, it was missing some parameters, so I reworked your package and added them.

What I did was add a new config file: tspath.json, in which you can use variables other than those of tsconfig.json.
I also added a few extra flags:

  • root: for a different root directory
  • absPath: to make all paths absolute

I still need to add an --env flag, but I'm getting there.

The codebase can be found here: https://github.com/pidz-development/tspath-aws-sam.

Best regards

Output dir should relative to root, not source dir

There's an issue here and next line:

this.appRoot = path.resolve(this.projectPath, this.projectOptions.baseUrl);

The outDir parameter should be added relative to the original location of tsconfig.json, not the baseUrl, which is used for module resolution.

The current version works accidentally for "baseUrl": "./", but changing it to e.g. "baseUrl": "./src" cause the following exception:
Error: ENOENT: no such file or directory, scandir 'F:\Repos\magiczny-miecz\MagicSword.Core\MagicSword.Core.Logic\ClientApp\src\dist\out-tsc' at Object.readdirSync (fs.js:759:3) at ParserEngine.walkSync (F:\Repos\magiczny-miecz\MagicSword.Core\MagicSword.Core.Logic\ClientApp\node_modules\tspath\src\parser-engine.js:260:24) at ParserEngine.execute (F:\Repos\magiczny-miecz\MagicSword.Core\MagicSword.Core.Logic\ClientApp\node_modules\tspath\src\parser-engine.js:101:14) at TSPath.processPath (F:\Repos\magiczny-miecz\MagicSword.Core\MagicSword.Core.Logic\ClientApp\node_modules\tspath\src\tspath.js:39:25) at Confirm.callback (F:\Repos\magiczny-miecz\MagicSword.Core\MagicSword.Core.Logic\ClientApp\node_modules\tspath\src\tspath.js:29:27) at Confirm.<anonymous> (F:\Repos\magiczny-miecz\MagicSword.Core\MagicSword.Core.Logic\ClientApp\node_modules\prompt-base\index.js:625:10) at runCallback (timers.js:696:18) at tryOnImmediate (timers.js:667:5) at processImmediate (timers.js:649:5)

while the output path here is still F:\Repos\magiczny-miecz\MagicSword.Core\MagicSword.Core.Logic\ClientApp\dist\out-tsc

Includes baseUrl in parsed path when it shouldn't

Great work on this well needed package!

I think there may be an issue with resolving paths. With the correct setup for paths I get an error.

So I have:

Project
    src
    dist

My tsconfig:

        "outDir": "dist",
        "baseUrl": "./",
        "paths": {
            "api/*": ["src/api/*"],
            "utilities/*": ["src/utilities/*"],
            "middleware/*": ["src/middleware/*"],
            "resolvers/*": ["src/resolvers/*"],
            "graphql-schemas/*": ["src/graphql-schemas/*"]
        },

The line of code:

import { graphqlSchema } from 'graphql-schemas/schemas';

Trace:

Error: Cannot find module '../src/graphql-schemas/schemas'

Expected parsed path: ../graphql-schemas/schemas

The paths that the parser are putting out are using the baseUrl as the root (it appears), but in reality they should be in relation to the directory in which they live? Like a reverse traverse upwards until they find the file?

And if i take the src out of the arrays, TypeScript wont' compile because it can't resolve it. Can't have one without the other :)

Not substitue path in d.ts

My code is something like this
dist/
src/
index.ts
hello.ts

where index.ts contains

export * from 'src/hello';

In dist/, after running tspath, index.d.ts still contains

export * from 'src/hello';

Path resolution has too many `..` when `paths` does not stem from project dir

What I try to do: Use some TS code somewhere in my project tree as a library by referring it by a paths mapping.

It seems that path resolution goes wrong when a paths reference does not stem from the project dir (where tsconfig.json is), e.g. has a .. in it.
Like this:

 "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@lib/*": ["./../lib/src/*"]
    },
    "outDir": "./dist",

In this case, the resolved path has one .. too much.

This also holds when shifting the baseUrl up:

 "compilerOptions": {
    "baseUrl": "./../",
    "paths": {
      "@lib/*": ["./lib/src/*"]
    },
    "outDir": "./dist",

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.