Skip to content

Instantly share code, notes, and snippets.

@aprilandjan
Forked from deejayy/CustomModuleLoader.ts
Created November 10, 2021 08:15
Show Gist options
  • Save aprilandjan/ecdc2c22e65efd3eeb20e415a00f26cd to your computer and use it in GitHub Desktop.
Save aprilandjan/ecdc2c22e65efd3eeb20e415a00f26cd to your computer and use it in GitHub Desktop.
Solves the problem with typescript->javascript compilation and module path aliases (compilerOptions.paths).
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);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment