Skip to content

Instantly share code, notes, and snippets.

@deejayy
Last active September 21, 2022 20:26
Show Gist options
  • Save deejayy/aa5f0cde76dc29f6b4127e60e74be2f2 to your computer and use it in GitHub Desktop.
Save deejayy/aa5f0cde76dc29f6b4127e60e74be2f2 to your computer and use it in GitHub Desktop.

Revisions

  1. deejayy revised this gist Sep 13, 2018. No changes.
  2. deejayy created this gist Sep 13, 2018.
    25 changes: 25 additions & 0 deletions CustomModuleLoader.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    import customModuleLoader = require('module');

    export class CustomModuleLoader {
    public cOptions: any = require('../tsconfig.json').compilerOptions;

    public replacePaths: any = {};

    constructor() {
    Object.keys(this.cOptions.paths).forEach(alias => {
    this.replacePaths[alias.replace(/\*.?/, '(.*)')] = this.cOptions.paths[alias][0].replace(/\*.?/, '$1');
    });

    (<any>customModuleLoader)._originalResolveFilename = (<any>customModuleLoader)._resolveFilename;

    (<any>customModuleLoader)._resolveFilename = (request: string, parent: customModuleLoader, isMain: boolean) => {
    Object.keys(this.replacePaths).forEach(matchString => {
    let regex = new RegExp(matchString);
    if (request.match(regex)) {
    request = [process.cwd(), this.cOptions.outDir, request.replace(regex, this.replacePaths[matchString])].join('/');
    }
    })
    return (<any>customModuleLoader)._originalResolveFilename(request, parent, isMain);
    }
    }
    };