From 667e81b5f99ef815dff80227ee9332ec1e74e9dd Mon Sep 17 00:00:00 2001 From: Maxime Grisole Date: Tue, 14 Nov 2023 22:12:30 +0100 Subject: [PATCH] fix: adapt imports replacement with tsconfig outDir depth #2706 --- lib/plugin/utils/plugin-utils.ts | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/lib/plugin/utils/plugin-utils.ts b/lib/plugin/utils/plugin-utils.ts index 138a7f85e..38ac08ac3 100644 --- a/lib/plugin/utils/plugin-utils.ts +++ b/lib/plugin/utils/plugin-utils.ts @@ -1,5 +1,5 @@ import { head } from 'lodash'; -import { isAbsolute, posix } from 'path'; +import {isAbsolute, join, posix} from 'path'; import * as ts from 'typescript'; import { PluginOptions } from '../merge-options'; import { @@ -16,6 +16,8 @@ import { isStringLiteral, isStringMapping } from './ast-utils'; +import {readFileSync} from "node:fs"; +import {normalize, sep} from "node:path" export function getDecoratorOrUndefinedByNames( names: string[], @@ -166,6 +168,7 @@ export function replaceImportPath( let relativePath = posix.relative(from, importPath); relativePath = relativePath[0] !== '.' ? './' + relativePath : relativePath; + relativePath = adaptPathWithConfig(relativePath); const nodeModulesText = 'node_modules'; const nodeModulePos = relativePath.indexOf(nodeModulesText); @@ -331,6 +334,24 @@ function isOptionalBoolean(text: string) { return typeof text === 'string' && text === 'boolean | undefined'; } +function adaptPathWithConfig(inputPath: string) { + try { + const rawConfig = readFileSync('tsconfig.json', 'utf8'); + const parsedConfig = JSON.parse(rawConfig); + const outDir = parsedConfig.compilerOptions.outDir; + + const outDirDepth = normalize(outDir) + .split(sep) + .map(() => '..') + .join(sep); + + return join(outDirDepth, inputPath); + } catch (error) { + console.error(error); + return inputPath; + } +} + /** * Converts Windows specific file paths to posix * @param windowsPath