@nestjs/cli
Version:
Nest - modern, fast, powerful node.js web framework (@cli)
89 lines (88 loc) • 3.64 kB
JavaScript
import { createRequire } from 'module';
import { dirname, posix } from 'path';
import * as tsPaths from 'tsconfig-paths';
import { TypeScriptBinaryLoader } from '../typescript-loader.js';
const require = createRequire(import.meta.url);
export function tsconfigPathsBeforeHookFactory(compilerOptions) {
const tsBinary = new TypeScriptBinaryLoader().load();
const { paths = {}, baseUrl = './' } = compilerOptions;
const matcher = tsPaths.createMatchPath(baseUrl, paths, ['main']);
return (ctx) => {
return (sf) => {
const visitNode = (node) => {
if (tsBinary.isImportDeclaration(node) ||
(tsBinary.isExportDeclaration(node) && node.moduleSpecifier)) {
try {
const text = getModuleSpecifierText(node.moduleSpecifier, sf);
if (!text) {
return node;
}
const result = getNotAliasedPath(sf, matcher, text);
if (!result) {
return node;
}
const moduleSpecifier = tsBinary.factory.createStringLiteral(result);
moduleSpecifier.parent = node.moduleSpecifier.parent;
if (tsBinary.isImportDeclaration(node)) {
const updatedNode = tsBinary.factory.updateImportDeclaration(node, node.modifiers, node.importClause, moduleSpecifier, node.assertClause);
updatedNode.flags = node.flags;
return updatedNode;
}
else {
const updatedNode = tsBinary.factory.updateExportDeclaration(node, node.modifiers, node.isTypeOnly, node.exportClause, moduleSpecifier, node.assertClause);
updatedNode.flags = node.flags;
return updatedNode;
}
}
catch {
return node;
}
}
return tsBinary.visitEachChild(node, visitNode, ctx);
};
return tsBinary.visitNode(sf, visitNode);
};
};
}
function getModuleSpecifierText(moduleSpecifier, sourceFile) {
if (!moduleSpecifier) {
return;
}
if (typeof moduleSpecifier.text === 'string') {
return moduleSpecifier.text;
}
const importPathWithQuotes = moduleSpecifier.getText(sourceFile);
if (!importPathWithQuotes) {
return;
}
return importPathWithQuotes.substring(1, importPathWithQuotes.length - 1);
}
function getNotAliasedPath(sf, matcher, text) {
let result = matcher(text, undefined, undefined, [
'.ts',
'.tsx',
'.js',
'.jsx',
]);
if (!result) {
return;
}
if (process.platform === 'win32') {
result = result.replace(/\\/g, '/');
}
try {
// Installed packages (node modules) should take precedence over root files with the same name.
// Ref: https://github.com/nestjs/nest-cli/issues/838
const packagePath = require.resolve(text, {
paths: [process.cwd(), ...(require.resolve.paths(text) ?? [])],
});
if (packagePath) {
return text;
}
}
catch {
// package resolution failed, fall through to relative path
}
const resolvedPath = posix.relative(dirname(sf.fileName), result) || './';
return resolvedPath[0] === '.' ? resolvedPath : './' + resolvedPath;
}