tsc-alias icon indicating copy to clipboard operation
tsc-alias copied to clipboard

Suggested fix for the Incorrect suffixing of node modules when a local import of the same name exists

Open U-4-E-A opened this issue 2 years ago • 4 comments

References #197 and #199.

Currently, both the following are treated the same: -

import React from "react"
import { MyReactComponent } from "./react"

Both will be suffixed: -

import React from "react.js"
import { MyReactComponent } from "./react.js"

This is due to the regex in utils/import-path-resolver.ts not differentiating between import/require statements that have local import syntax and those that do not (and are therefore node modules imports): -

const anyQuote = `["']`;
const pathStringContent = `[^"'\r\n]+`;
const importString = `(?:${anyQuote}${pathStringContent}${anyQuote})`;

This simply matches any string between 2 quotes. Please resolve this issue by amending the regex to that below. The excludeLocalImportSyntax regex excludes strings that start with .. This could be expanded out to ./ or ../ for local imports but I see no need as any local import should start with . (tested).

const anyQuote = `["']`;
const excludeLocalImportSyntax = `[(?!\.)]`;
const pathStringContent = `[^"'\r\n]+`;
const importString = `(?:${anyQuote}${excludeLocalImportSyntax}${pathStringContent}${anyQuote})`;

U-4-E-A avatar Mar 03 '24 14:03 U-4-E-A

I had the same issue, this fixed it. going to use patch-package til the author has time to update.

pcfreak30 avatar Mar 13 '24 14:03 pcfreak30

For anyone interested:

patches/tsc-alias+1.8.8.patch:

diff --git a/node_modules/tsc-alias/dist/utils/import-path-resolver.js b/node_modules/tsc-alias/dist/utils/import-path-resolver.js
index ebaf620..227d4c7 100644
--- a/node_modules/tsc-alias/dist/utils/import-path-resolver.js
+++ b/node_modules/tsc-alias/dist/utils/import-path-resolver.js
@@ -5,8 +5,9 @@ const normalizePath = require("normalize-path");
 const fs_1 = require("fs");
 const path_1 = require("path");
 const anyQuote = `["']`;
+const excludeLocalImportSyntax = `[(?!\.)]`;
 const pathStringContent = `[^"'\r\n]+`;
-const importString = `(?:${anyQuote}${pathStringContent}${anyQuote})`;
+const importString = `(?:${anyQuote}${excludeLocalImportSyntax}${pathStringContent}${anyQuote})`;
 const funcStyle = `(?:\\b(?:import|require)\\s*\\(\\s*(\\/\\*.*\\*\\/\\s*)?${importString}\\s*\\))`;
 const globalStyle = `(?:\\bimport\\s+${importString})`;
 const fromStyle = `(?:\\bfrom\\s+${importString})`;

pcfreak30 avatar Mar 13 '24 14:03 pcfreak30

@U-4-E-A Your fix breaks all tests. Please send a PR. THANKS

justkey007 avatar Mar 14 '24 10:03 justkey007

I don't have a PR available, sorry. My own testing was simply done by running the CLI on my packages.

U-4-E-A avatar Mar 20 '24 15:03 U-4-E-A

This should be closed now that we pushed a fix #218

dvqc avatar May 14 '24 15:05 dvqc