0.0.7 • Published 1 year ago

ts-alias v0.0.7

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

Typescript Aliases Parser

A NodeJS library to parse, process and convert Typescript aliases from tsconfig.json.

npm npm

Use cases

We all agree that module aliases are useful to maintain a clean and readable code.

But it's frequent that, in large projects, you have to define your same aliases in multiple tools in order to ensure everything runs correctly.

Also, some tools doesn't support defining custom node_module paths for these aliases, which can be locking in some complex projects.

I wrote this library to avoid the redondancy between my tsconfig.js, Webpack and module-alias configuration in my projects.

I assumed that the tsconfig.js format is the most universal, and can be reliably converted to aliases list for other tools like module-alias and the Webpack package.

By parsing your tsconfig, defining custom rules if necessary, and exporting them for your other aliasing tools, it lightens your maintenance and debugging work.

Are you using this module for another purpose ? Don't hesitate to create a PR so we can list it here!



Install

npm i --save ts-alias

Instanciate

The constructor loads the Typescript aliases in the memory. It can be loaded by two different ways:

From a tsconfig.json file

  1. By default, it will search the tsconfig in the current working directory of the process (process.cwd()).
import Aliases from 'ts-alias';
const aliases = new Aliases();
  1. You can specify in path of the directory containing the tsconfig with the rootDir option. This path can be absolute, or relative (from the process working directory).
const aliases = new Aliases({ 
    rootDir: './packages/module-containing-a-tsconfig' 
});
  1. It's possible to directly provide the tsconfig file path:
const aliases = new Aliases({ 
    rootDir: './packages/module-containing-a-tsconfig/tsconfig.json' 
});

An Error will be throwed if rootDir doesn't exists.

From an AliasList object

If for any reason, you already loaded the tsconfig aliases in memory, you can provide them via the aliases option:

const list = [{
    alias: '@server',
    // A list of destination paths
    pathnames: ['./src/server'],
    // If exact = true, only "@server" will be matched
    // If exact = false, "@server" and "@server/*" will be matched
    exact: false
}, {
    alias: 'react',
    // pathnames can also be module names
    pathnames: ['preact'],
    exact: true
}]

const aliases = new Aliases({ aliases: list });

Specify the module path

As you saw upper, alias destinations can also be package names. Thanks to the modulesDir option, you can define in which node_modules directory your package should be looked for.

const aliases = new Aliases({
    modulesDir: ['./node_modules', '../../global_node_modules']
});

Warning: This feature is experimental. It could lead to resolution problems in some cases.

Note: Only relative paths are supported for now.

Debug

Are you facing to a resolution problem ? Do you balieve these is a bug in this lib ?

That's not impossible 🤔

To better understands what ts-alias actually does in your case, you can enable advanced logs with the debug option:

const aliases = new Aliases({
    debug: true
});

Test if a path can be shorten with an alias

public isAliased( filename: string ): boolean;
aliases.isAliased("./src/server/services/user");
// Result: true

aliases.isAliased("./src");
// Result: false

Shorten / Replace real path by alias

public apply( realpath: string, strict?: false ): string;
public apply( realpath: string, strict: true ): string | null;
public apply( realpath: string, strict?: boolean ): string | null;
aliases.apply("./src/server/services/user");
// Result: "@server/services/user"

aliases.apply("react");
// Result: "./node_modules/react"

When the realpath couldn't be replaced with an alias:

  • When strict is true, null will be returned.
  • Otherwise, the original realpath will be returned, without any alias

Test if a path contains an alias

 public containsAlias( filename: string ): boolean;
aliases.containsAlias("@server/services/user");
// Result: true

aliases.containsAlias("./src/server/services/user");
// Result: false

Replace alias by real path

public realpath( request: string, strict?: false): string;
public realpath( request: string, strict: true): string | null;
public realpath( request: string, strict?: boolean): string | null;
aliases.realpath("@server/services/user");
// Result: "/home/gaetan/projects/myproject/src/server/services/user"

aliases.realpath("./node_modules/react");
// Result: "preact"

Convert the aliases list for Webpack 5

const webpackAliases = aliases.forWebpack();

module.export = {
    ...
    resolve: {
        alias: webpackAliases
    }
    ...
}

You can pass options in forWebpack():

const webpackAliases = aliases.forWebpack({

    // The path where to resolve node modules
    modulesPath: string,

    // Set to true if you want forWebpack to output the package name (ex: `ts-alias/src/index.ts`) instead of the path to node_modules (ex: `./node_modules/ts-alias/src/index.ts`)
    shortenPaths: boolean,
    
    // When set to true, it will return a { aliases, externals } object with the aliases for webpack,
    //  and a nodeExternals function for webpack
    nodeExternals: boolean
});

Convert the aliases list for module-alias

import moduleAlias from 'module-alias';

moduleAlias.addAliases( aliases.forModuleAlias() );


Changelog

0.0.7 (16 December 2022)

  • Use a TOutputOptions object for passing options in forWebpack()
public forWebpack<TNodeExternals extends boolean>({ 
    modulesPath, shortenPaths, nodeExternals 
}: TOutputOptions<TNodeExternals>): TWebpackOutput<TNodeExternals>
  • Added a shortenPaths option for forWebpack() Set to true if you want forWebpack to output the package name (ex: ts-alias/src/index.ts) instead of the path to node_modules (ex: ./node_modules/ts-alias/src/index.ts)

  • Store aliases in array instead of indexing by alias. It allows you to create an exact & prefix version for the same alias. By example:

{
    // Exact version: only match "@server"
    "@server": ["./server"],
    // Prefix version: match any import that starts by "@server/"
    "@server/*": ["./server/*"],
}

TODO

  • Tests (the current version lacks of tests)
  • Strict types checking
  • Better path resolving (traverse extends)