GithubHelp home page GithubHelp logo

davestewart / alias-hq Goto Github PK

View Code? Open in Web Editor NEW
329.0 4.0 12.0 1.77 MB

The end-to-end solution for configuring, refactoring, maintaining and using path aliases

Home Page: https://davestewart.co.uk/projects/open-source/alias-hq/

License: MIT License

JavaScript 100.00%
webpack rollup jest vue configuration aliases vscode webstorm

alias-hq's People

Contributors

bjoluc avatar davestewart avatar diegoulloao avatar gormonn avatar ianvs avatar leoj3n avatar pankajpatel avatar stigkj 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

alias-hq's Issues

hq-alias in jest config file does not work

Still getting errors from jest when running tests after integrating this into my jest.config.js file

error from jest:
Test suite failed to run

Cannot find module '@/error' from 'src/generator/prompt/index.ts'
// jest.config.js: 
import hq from 'alias-hq'

const config = {
	verbose: true,
	testEnvironment: 'node',
	modulePathIgnorePatterns: ['dist'],
	moduleNameMapper: hq.get('jest'),
}

export default config

How to set up w/ Docusaurus

I ended up using https://github.com/atomicpages/docusaurus-plugin-module-alias to get alias-hq to work with https://docusaurus.io

// @ts-check
// Note: type annotations allow type checking and IDEs autocompletion

...
const hq = require('alias-hq');

/** @type {import('@docusaurus/types').Config} */
const config = {
  ...
  plugins: [
    [
      'docusaurus-plugin-module-alias',
      {
        alias: hq.get('webpack'),
      },
    ],
  ],
  ...
};

module.exports = config;

Just wanted to record this for anyone else who might need it in the future

Improve formatting when adding paths

Right now when you add paths, you get the whole format object back, which makes it tricky to see what has been added

Would be cool to colorise only the added paths.

CLI code to update `tsconfig.json` paths will remove any comments

Background

Because tsconfig.json supports // comments simply loading and then saving JSON to the file will replace the file's contents and so remove any comments:

https://github.com/davestewart/alias-hq/blob/master/cli/utils/file.js#L20

Proposal

Replace only the paths part of the file.

Ideas:

  • see if the TypeScript's own tools added in #37 have a solution to this
  • programatically find and replace portions of the file using regexp / string methods
  • use some kind of AST or lexer (3rd-party or something home-rolled for speed, counting brackets in and out)

Aliases to a node module are mapped as relative to base path

tsconfig.json

	"baseUrl": "./src/js/"
	...
      "handlebars": ["handlebars/runtime"],

output of hq.get('webpack')

  handlebars: '/Users/nick.bolles/Code/repo/src/js/handlebars/runtime',

this should stay as

  handlebars: 'handlebars/runtime',

it looks like setting the value to "handlebars": ["../../node_modules/handlebars/runtime"], in the tsconfig works, but that's not ideal.

Running node scripts with `alias-hq/init` from subdirectories fails

Originally posted by @andidev in #46 (comment)

It looks like the solution for loading Alias HQ via a require flag in Node is causing issues when running scripts not in root project folder; package.json does not seem to be found.

This makes running scripts from WebStorm fail so we cannot still replace tsconfig-paths with alias-hq fully ๐Ÿ˜ž

Screenshot of this issue reproduced with alias-hq from terminal and how same works with tsconfig-paths:

image

I am guessing this is caused by how alias-hq looks for package.json is different from tsconfig-paths, or maybe tsconfig-paths doesn't load the package.json at all since it has no settings saved there? Not sure.

Is it possible to change that in case package.json is not found it does not throw an error? Oor maybe it looks for a package.json file further up in the directory tree until it finds one?

I can provide a PR for this if it's ok

Changelog is out of date

I saw that I'm a few versions behind in my project, and am trying to figure out what changed in the last two patch releases, but the releases are not updated and neither is the changelog. I can look through commits in the history, but it's definitely nice to have a record of releases somewhere.

Add types

I tried to use your package inside a jest.config.ts, but it does not seem to have types for itself? Would be quite nice if that would be possible.

Load should also accept a ready imported TSConfig.

In my case I am importing a TSconfig for other stuff in the build script, and I don't see why I couldn't just pass the JSON directly to the loading, instead of giving it a name instead?

import * as TSconfig from "./tsconfig.dir.json"

Btw, you got the right idea here.
There needs to be a single source of truth for these things, and all the other libraries need to just infer from it.
Every other library seems to spread thoses aliases into different parts.

Personally, I think Yarn (Berry) has it right, by keeping the aliases as the other packages, but it doesn't work so well with Rollup.

TSConfig is the next best thing

Tools to rename and remove aliases

Background

A tool to manipulate both the aliases and the source code would be useful:

Rename

I currently have a project where the path aliases are:

{
  "foo/*": ["src/foo/*"],
  "bar/*": ["src/bar/*"],
  "baz/*": ["src/baz/*"],
}

I would like them to be:

{
  "@foo/*": ["src/foo/*"],
  "@bar/*": ["src/bar/*"],
  "@baz/*": ["src/baz/*"],
}

Remove

Also, some overly-specific aliases that I would like removed:

{
  "foo/*": ["src/foo/*"],
  "bar/*": ["src/foo/bar/*"],     // <-- don't need this
  "baz/*": ["src/foo/bar/baz/*"], // <-- or this
}

Proposal

Having tools to update these would be great.

UI

Not sure how it would look in the CLI right now, perhaps:

  • pick from a list
  • answer multiple questions, or maybe use the "editor" prompt
  • for rename, check for collisions

Then process.

Processing

The source code should be updated when aliases are modified:

  • each file will need to be checked.

Rename should be:

  • checking the first segment and rename

Removal would need to:

  • check if there is a more specific alias and use that
  • if not, use the relative path

Refactor CLI to a different module?

Love the idea of the module, but for people who don't want to use the CLI ... quite a lot of modules are installed:

Yeah it's 48 thousand lines, I can't paste it in GitHub, Gist, or Pastebin, but the bulk of them come from jscodeshift, which isn't needed for people not looking to use the CLI.

Write JSON 5

Background

Right now, we can't write JSON 5 (i.e. comments) back to file.

Apparently even the JSON 5 maintainer doesn't want to touch this.

However, as our use case is so specific we could probably write back to the file using regexp.

Proposal

Something along these lines:

const input = `{
  "example": true,
  "compilerOptions": {
    "target": "esnext",
    "baseUrl": "src",
    "paths": {
      "@/*": ["/*"],
      "@packages/*": ["../packages/*"],
      "@classes/*": ["classes/*"],
      "@app/*": ["app/*"],
      "@data/*": ["app/data/*"],
      "@settings": ["app/settings.js"],
      "@services/*": [
        "app/services/*",
        "../packages/services/*"
      ],
      "@views/*": ["app/views/*"]
    }
  }
}`
    
const rxPaths = /(\s+"paths":\s*)(\{([^}]*)\})/
const rxSpace = /^([ \t]+)"/m

const space = input.match(rxSpace)[1].repeat(3)
const output = input.replace(rxPaths, (match, prefix, block, paths) => {
    console.log(JSON.parse(block))
    return `${prefix}{ ... }`
})

console.log(output)
{
  "example": true,
  "compilerOptions": {
    "target": "esnext",
    "baseUrl": "src",
    "paths": { ... }
  }
}

When writing back to the file, I think we only need to add new aliases at the end, so in theory we don't even need to parse the contents, just append new paths.

Consider using older TS version

After adding typescript as a dependency in #37, I found that updating alias-hq also updated the version of typescript being used in my project, which caused some failures since I went from 4.4 to 4.5, and typescript treats minor version updates as breaking. I can solve this by using 4.4.x in my package.json, but this could cause confusion for others as well, so what do you think about using an older version of typescript that still supports the methods needed, so that an accidental upgrade is less likely?

Refactor aliases property naming

Background

Right now, alias are declared in various ways:

{
  alias: '@name',
  path: './src/path/',
}
{
  alias: '@name',
  absPath: 'drive/project/src/some/path/',
  relPath: 'src/path/',
}

Problem

The issue arises when we start referring to aliases' "alias" property:

const alias = aliases.get('@name')
const alias = alias.alias // <-- confusing double entry
const path = alias.path

Because we are working most of the time with objects, it becomes ambiguous which one is which.

Proposal

It could be better to refactor aliases, so any reference to alias would always be an "Alias" Object with name and path properties:

const alias = getAlias()
const { name, path } = alias

With some initial tests, it looks like there could be confusion either way, but the second โ€“ more formal โ€“ approach is better for writing CLI code, as "aliases" (objects with name and path properties) can be stored, filtered, retrieved, etc:

const alias = aliases.get('@name')
const { name, path } = alias
console.log(alias, name, path)

This would be a breaking change, but better to get this done now vs later.

Accessing paths from a `tsconfig.json` that extends another `tsconfig.base.json` with the alias paths

๐Ÿ‘‹ Hey, great library! I've got this working for the most part in a monorepo structure, but I'm having trouble with hq.get('any') returning {} when used inside the /package/* directory roots. This is because the tsconfig.json inside each package extends the tsconfig.base.json at the monorepo root where I have my paths configured. Because the tsconfig.json doesn't explicitly contain the paths, the result is {} and thus I'm having issues plugging in aliases in some package-specific processes like Jest.

For the most part everything else works fine, and I've got a nice clean, centralised alias structure which all runs and builds fine - just trying to figure out this last piece.

Here's the structure:

monorepo/
    ...
    tsconfig.base.json (1)
    packages/
        client/
            ...
            tsconfig.json (2)
        components/
            ...
            tsconfig.json (3)

In the monorepo root I've got a couple processes that consume the aliases set in tsconfig.base.json (1), e.g. a shared Storybook across all packages. In tsconfig.base.json I have my alias paths set up like so:

{
    "compilerOptions": {
        ...
        "rootDir": "./",
        "baseUrl": "./packages",
        "paths": {
            "@client/*": ["../packages/client/*"],
            "@components/*": ["../packages/components/*"]
        }
    }
}

and in my packages, e.g. client, I have a tsconfig.json (2) that extends the root tsconfig.base.json (3):

{
    "extends": "../../tsconfig.base.json",
    "compilerOptions": {
        ...
        "baseUrl": "../",
     }
}

This works in that my code compiles, runs, builds etc and resolves the aliases, but as I've said, if I try and use hq.get('any') ('webpack', 'jest', w/e) in any of the package roots it returns empty. It returns the paths just fine in the root. Sorry for the repetitive explanation, I hope I've made my issue clear.

Thanks again!

Could not find a declaration file for module 'alias-hq'.

Hi, when trying to use this with a SolidJS project, I'm receiving the following typescript error-

'/node_modules/alias-hq/src/index.js' implicitly has an 'any' type.
  There are types at '/node_modules/alias-hq/types/index.d.ts', but this result could not be resolved when respecting package.json "exports".
The 'alias-hq' library may need to update its package.json or typings.ts(7016)

alias-hq keep crashing

Getting these errors when I try to "update source code"

C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\routes\api\reviews.js
  โ€บ ../../controllers/reviewsController
  โ€บ controllers\reviewsController
 ERR C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\levenary\index.flow.js Transformation error (Unexpected token, expected ";" (1:8))
SyntaxError: Unexpected token, expected ";" (1:8)
    at Object._raise (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:757:17)
    at Object.raiseWithData (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:750:17)
    at Object.raise (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:744:17)
    at Object.unexpected (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:8834:16)
    at Object.semicolon (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:8816:40)
    at Object.parseExpressionStatement (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:11743:10)
    at Object.parseStatementContent (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:11344:19)
    at Object.parseStatement (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:11210:17)
    at Object.parseBlockOrModuleBlockBody (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:11785:25)
    at Object.parseBlockBody (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:11771:10)
 ERR C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\tar\tar.js Transformation error (Legacy octal literals are not allowed in strict mode (108:10))
SyntaxError: Legacy octal literals are not allowed in strict mode (108:10)
    at Object._raise (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:757:17)
    at Object.raiseWithData (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:750:17)
    at Object.raise (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:744:17)
    at Object.readNumber (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:8340:14)
    at Object.getTokenFromCode (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:8093:14)
    at Object.getTokenFromCode (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:4680:18)
    at Object.nextToken (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:7625:12)
    at Object.next (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:7550:10)
    at Object.eat (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:7555:12)
    at Object.parseObjectProperty (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:10635:14)
 ERR C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\client\node_modules\.bin\sha.js Transformation error (Unexpected token, expected "," (2:18))
SyntaxError: Unexpected token, expected "," (2:18)
    at Object._raise (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:757:17)
    at Object.raiseWithData (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:750:17)
    at Object.raise (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:744:17)
    at Object.unexpected (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:8834:16)
    at Object.expect (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:8820:28)
    at Object.parseCallExpressionArguments (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:9865:14)
    at Object.parseSubscript (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:9785:31)
    at Object.parseSubscript (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:1032:24)
    at Object.parseSubscripts (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:9711:19)
    at Object.parseExprSubscripts (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:9694:17)
 ERR C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\client\node_modules\levenary\index.flow.js Transformation error (Unexpected token, expected ";" (1:8))
SyntaxError: Unexpected token, expected ";" (1:8)
    at Object._raise (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:757:17)
    at Object.raiseWithData (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:750:17)
    at Object.raise (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:744:17)
    at Object.unexpected (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:8834:16)
    at Object.semicolon (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:8816:40)
    at Object.parseExpressionStatement (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:11743:10)
    at Object.parseStatementContent (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:11344:19)
    at Object.parseStatement (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:11210:17)
    at Object.parseBlockOrModuleBlockBody (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:11785:25)
    at Object.parseBlockBody (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:11771:10)
 ERR C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\client\node_modules\prop-types\prop-types.min.js Transformation error (targetPath.startsWith is not a function)
TypeError: targetPath.startsWith is not a function
    at toAlias (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\alias-hq\cli\modules\source\transformer\paths.js:27:18)
    at NodePath.<anonymous> (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\alias-hq\cli\modules\source\transformer\transformer.js:38:25)
    at C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\jscodeshift\src\Collection.js:75:36
    at Array.forEach (<anonymous>)
    at Collection.forEach (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\jscodeshift\src\Collection.js:74:18)
    at transform (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\alias-hq\cli\modules\source\transformer\transformer.js:34:14)
    at newTransform (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\vue-jscodeshift-adapter\src\jscodeshift-mode.js:9:14)
 ERR C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\client\node_modules\shallowequal\index.original.js Transformation error (Unexpected token, expected "(" (3:38))
SyntaxError: Unexpected token, expected "(" (3:38)
    at Object._raise (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:757:17)
    at Object.raiseWithData (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:750:17)
    at Object.raise (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:744:17)
    at Object.unexpected (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:8834:16)
    at Object.expect (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:8820:28)
    at Object.parseFunctionParams (C:\Users\xxxxx\WebstormProjects\xxxxx-postgres\node_modules\@babel\parser\lib\index.js:11947:10)
    at Object.parseFunction (C:\Use

my config is

{
  "compilerOptions": {
    "baseUrl": "",
    "paths": {
      "Models/*": ["Database\\Models/*"],
      "controllers/*": ["controllers/*"],
      "config/*": ["config/*"],
      "middleware/*": ["middleware/*"],
      "utils/*": ["utils/*"]
    }
  }
}

Deprecated packages in 5.4.0

The following warnings are issued when I install a working project that uses [email protected] :

npm WARN deprecated [email protected]: See https://github.com/lydell/source-map-url#deprecated
npm WARN deprecated [email protected]: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated [email protected]: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated [email protected]: See https://github.com/lydell/source-map-resolve#deprecated

Investigating the source of these dependencies shows this:

npm list [email protected] [email protected] [email protected]
ts-template@ /Users/Invented/Path/To/Project
โ”œโ”€โ”ฌ [email protected]
โ”‚ โ””โ”€โ”ฌ [email protected]
โ”‚   โ””โ”€โ”ฌ [email protected]
โ”‚     โ””โ”€โ”ฌ [email protected]
โ”‚       โ””โ”€โ”ฌ [email protected]
โ”‚         โ”œโ”€โ”€ [email protected]
โ”‚         โ”œโ”€โ”€ [email protected]
โ”‚         โ””โ”€โ”€ [email protected]

I believe updating updating alias-hq dependency jscodeshift from 0.10.0 to 0.13.0 will solve the import of deprecated packages but I leave that your judgement and choice to update. Many thanks for this great package!

[Plugin proposal] eslint-import-alias

See https://github.com/steelsojka/eslint-import-alias

I have the code ready because I needed it for my codebase!

Desired output:

// Before
{
  "~actions/*": ["src/actions/*"],
  "~ui/*": ["src/components/ui/*"],
}
  
// After  
[
  { alias: '~actions', matcher: '^src\/actions' },
  { alias: '~ui', matcher: '^src\/components\/ui' },
]

It should look something like this:

const { toArray } = require('../../utils')

// @see https://github.com/steelsojka/eslint-import-alias#configure
function callback (name, [path], config, options) {
  return {
    alias: name.replace('/*', ''),
    matcher: '^' + path.replace('/*', '').replaceAll('/', '\\/').replaceAll(/\.([a-zA-Z]+)/g, '\\.$1'),
  }
}

module.exports = function (config, options) {
  return toArray(callback, config, options)
}

And the test:

module.exports = [
  function () {
    const expected = [
      {
        alias: '@',
        matcher: '^'
      },
      {
        alias: '@packages',
        matcher: '^..\\/packages'
      },
      {
        alias: '@classes',
        matcher: '^classes'
      },
      {
        alias: '@app',
        matcher: '^app'
      },
      {
        alias: '@data',
        matcher: '^app\\/data'
      },
      {
        alias: '@settings',
        matcher: '^app\\/settings\\.js'
      },
      {
        alias: '@services',
        matcher: '^app\\/services'
      },
      {
        alias: '@views',
        matcher: '^app\\/views'
      }
    ]
    return { expected }
  },
]

Let me know if you're interested in me adding the plugin + docs to the codebase!

Plugin callback function could be improved

The current plugin utils callback signature is as follows:

function callback (alias, config, options) {
  const { rootUrl, baseUrl, paths } = config // note, these are the *alias* paths!
  return {
    name: alias.replace('/*', ''),
    path: paths[0].replace('/*', '')
  }
}

This is strange as both alias and paths are members of each tsconfig line:

{
  baseUrl,
  {
    alias => paths,
    ...
  }
}

As paths have to be used for each call, it might be more intuitive to simply include paths as part of the callback signature, rather than having to destructure:

function callback (alias, paths) {
  return {
    name: alias.replace('/*', ''),
    path: paths[0].replace('/*', '')
  }
}

Additionally, the property config could potentially also be called urls and they could be base and root:

function callback (alias, paths, { base, root }) {
  ...
}

These changes would require updating of utils and plugins:

They would also require a major version bump as they would break custom plugins.

CI Integration

Is there any way to set-up alias-hq CLI as a CI tool?

Basically, Iโ€™d want to use GitLab pipelines to run alias-hq and fail if a path alias is not used, to enforce that the entire project always uses them.

So, the requirements would be:

  1. Run some sort of command (e.g. yarn run alias-hq --check)
  2. Command uses exit code 1 if some issue was found
  3. Command uses exit code 0 if no issue was found

Thanks for the tool BTW, really useful and well-done

Indentation issues?

Hey @pankajpatel,

I noticed in your commit that indentation was updated along with aliases.

Was this something you did yourself, or was it done by Alias HQ?

If Alias did this, I'd see that as a bug, and would like to put it right.

Tsconfig parser does not support Node.js-style resolution of the `extends` field

#65 removed support for Node.js-style resolution of the tsconfig extends field โ€“ something that TypeScript can do. Implementing this from-scratch is not entirely trivial, but get-tsconfig has it all. @davestewart Since you decided against get-tsconfig, I'm not sure if there's a reason not to use it in this project? If not, I'm happy to submit a PR (I'm desperately depending on module resolution in extends ๐Ÿฅฒ). Just drop me a thumbs-up reaction here if get-tsconfig would also work.

Change JSON parser to JSON5

Currently aliasHQ seems to be using a parser that does not recognizes comments in JSON. This can be problematic as many projects that might be allowing comments in their tsconfigs suddenly won't be able to do so if they use aliasHQ for parsing. This issue is to address that problem.

Jest plugin does not properly handle modules in parent dir

๐Ÿ‘‹ big fan of this package! Ran into a subtle issue in my (unconventional) repo structure.

Problem

Consider this highly simplified and somewhat contrived example:

.
โ”œโ”€โ”€ README.md
โ”œโ”€โ”€ app
โ”‚ย ย  โ”œโ”€โ”€ jest.config.js
โ”‚ย ย  โ”œโ”€โ”€ package.json
โ”‚ย ย  โ””โ”€โ”€ src
โ”‚ย ย      โ””โ”€โ”€ index.test.js
โ”œโ”€โ”€ jest.config.js
โ”œโ”€โ”€ jsconfig.json
โ”œโ”€โ”€ package.json
โ”œโ”€โ”€ src
โ”‚ย ย  โ”œโ”€โ”€ index.test.js
โ”‚ย ย  โ””โ”€โ”€ utils
โ”‚ย ย      โ””โ”€โ”€ some-util.js
โ””โ”€โ”€ yarn.lock

The bulk of the code lives in src, though there's also an app directory which functionally is its own package. However, it does share modules (and aliases) with src. Consider this jsconfig.json:

{
  "compilerOptions": {
    "paths": {
      "@utils/*": ["./src/utils/*"],
      "@app/*": ["./app/src/*"]
    }
  }
}

Both the top-level package and app have their own set of tests and corresponding jest.config.js files. In the top-level config, I would expect (and do correctly get!) the following moduleNameMapper value generated by alias-hq:

{
  '^@utils/(.*)$': '<rootDir>/src/utils/$1',
  '^@app/(.*)$': '<rootDir>/app/src/$1'
}

Likewise for app, I would expect this in its config (app/jest.config.js):

{
  '^@utils/(.*)$': '<rootDir>/../src/utils/$1',
  '^@app/(.*)$': '<rootDir>/../app/src/$1'
}

However, I instead get this:

{
  '^@utils/(.*)$': 'src/utils/$1',
  '^@app/(.*)$': 'app/src/$1'
}

Root cause

This seems to be due to the Jest plugin's implementation using path.join:

return join('<rootDir>', baseUrl, path)

When baseUrl is .., join removes the <rootDir> segment entirely. However, in this case (I think) we always want that to exist. Paths like <rootDir>/../src/utils/$1 resolve just fine with Jest's parser.

I've created a reproduction repo matching this described case for easier testing. I also have a branch up which (from what I can tell) fixes the issue - happy to open a PR if you think this is sufficient.

Possible misconfiguration

I wasn't entirely sure how to configure alias-hq for this sort of situation. I did the following in app/jest.config.js:

const {
  get: getModuleAliases,
  config: aliasConfig,
  load: loadAliasConfig,
} = require('alias-hq');
const path = require('path');

loadAliasConfig(path.resolve('../jsconfig.json'));
aliasConfig.baseUrl = '..';

module.exports = {
  roots: ['<rootDir>/src'],
  moduleNameMapper: getModuleAliases('jest'),
};

(I think) I had to manually point to jsconfig.json since it's not in a standard location relative to this config. I also manually set a baseUrl so that paths would be set relative to the parent dir. Still fairly new to this package so please let me know if there's a better / simpler way to configure this!

Happy to clarify any details - thanks!

Config is being overwritten rather than updated

Eeeek!

This one slipped through.

When the CLI tool is being used to update ts/jsconfig it is overwriting the entire file, rather than updating compilerOptions.

Will need to fix and back-publish if required.

Paths not working in Vercel Serverless

I deployed a started app in order to test it with vercel serverless, but I get a not found module error so I assume alias-hq is not working with Vercel.

Do you know about any issues when deploying to Vercel?

Development version vercel dev works fine in localhost.
Also in an isolated environment (not vercel dev, just node in localhost)

Vercel deploy screenshots

Error
Captura de Pantalla 8

App main file
Captura de Pantalla 9

tsconfig.json
Captura de Pantalla 10

All looks fine for me.

Error! Unexpected token ] in "tsconfig.json" at position 666

My tsconfig.json is :

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "lib": ["dom", "es2015", "esnext"],
    "outDir": "dist",
    "jsx": "react",
    "baseUrl": "./src",
    "paths": {
      "@src/*": ["src/*"],
      "@sections/*": ["src/app/sections/*"],
      "@app/*": ["src/app/*"]
    },
    "strict": true,
    "sourceMap": true,
    "skipLibCheck": true,
    "noImplicitAny": false,
    "noImplicitThis": false,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "allowJs": true
  },
  "include": ["src/**/*"],
  "exclude": [
    "src/index.js",
    "dist",
  ]
}

Executing alias-hq CLI :

./node_modules/.bin/alias-hq 

  == Alias HQ ==

  Error! Unexpected token ] in "tsconfig.json" at position 666

  Edit the file to fix this, then try again

Why? How to solve the problem?

typescript : v.4.1.5

Refactor to TypeScript

Background

Refactoring to TypeScript would be useful for two main reasons:

  1. Types for consumers of the lib
  2. Types for the CLI portion of the lib

Proposal

Convert to TypeScript in several stages:

  • Lib + plugins
  • CLI
  • Tests

Notes

Should aim for this as 7.0.0

Incorrect type for `load` function

The generated type for the load function is marked as value?: undefined but it should actually be value? string.

The generated type looks like this:

/**
 * Load config
 *
 * @param   {undefined}         value     Pass no value for to determine config file automatically
 * @param   {string}            value     Pass an absolute path to load from alternate location
 * @returns {object}                      The Alias HQ instance
 */
export function load(value?: undefined): object;

I believe the JSDoc here is incorrect, the value param should be combined into one and written as [value] instead to mark as optional, according to the docs: https://jsdoc.app/tags-type.html

The code line in question is here:

* @param {undefined} value Pass no value for to determine config file automatically

Simplify CLI menus

Right now, the main menu has these options:

  • Setup
    • Configure paths
    • Update source code
      • 5 x menu items
  • Integrations

This is problematic in several ways:

  • it combines source code updating with "configuration"
  • the source code menu is buried with multiple options
  • the source code configuration makes is a little convoluted, as the user HAS to set the settings each time
  • it makes the configuration documentation very long, when a user may not need to update source code

A better menu setup that would solve all these issues would be:

  • Configure paths
  • Setup integrations
  • Update source code

Add tool to rewrite source files

Requirement

The final piece in the toolset would be to rewrite project source code with updated aliases.

This could (hopefully) be accomplished fairly easily with a CLI tool and simple find and replace, or a codemod (see links).

Proposal

Aim:

  • rewrite imports using aliases
  • rewrite only non-aliased paths

Nice to have:

  • simplify already-aliased paths if possible (so @/core/services becomes @services)
  • some way to determine whether a path is or isn't aliased
    • perhaps alias ../ but not ./ because they are "local"
    • but what if in the same logical group, for example ../models/user.js ?
    • maybe have rules, such as:
      • a distance limit, such as max traversal ../../../
      • some way to work out common ancestors
      • a way to determine group boundaries, such as a dynamic checklist in the CLI:
        [ ] models
        [x] modules
        [ ] services
      • or perhaps a config file, such as alias-hq.rc
      • or both (CLI reads/writes to the config file)

Constraints:

  • handle import and require()
  • only rewrite body-level imports

TBC:

  • options / config which allow the user some control over this

Links

Rollup integration uses `name`, `path` instead of `find`, `replacement`

This seems like a very cool tool, and I'm getting started using it, but having some trouble with rollup.

I'm building my app with vite, which allows a resolve.alias setting (https://vitejs.dev/config/#resolve-alias) that is passed to @rollup/plugin-alias. However, when I run hq.get('rollup'), I get an array like this:

[
  { name: '@api', path: '/path/to/src/api' },
  {
    name: '@components',
    path: '/path/to/src/components'
  }
]

But rollup wants the objects to have keys of find and replacement. Debugging via the cli results in the right thing, just not hq.get(). Am I doing something incorrectly? Thanks!

Edit: I just found that hq.get('rollup', { format: 'object' }) will meet my needs, but I'll leave this open in case you'd like to look into it.

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.