justkey007 / tsc-alias

Replace alias paths with relative paths after typescript compilation
MIT License
876 stars 63 forks source link

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

Closed U-4-E-A closed 3 months ago

U-4-E-A commented 6 months ago

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})`;
pcfreak30 commented 5 months ago

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

pcfreak30 commented 5 months ago

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})`;
justkey007 commented 5 months ago

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

U-4-E-A commented 5 months ago

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

dvqc commented 3 months ago

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