diff --git a/tsc/internal/ast/utilities.go b/tsc/internal/ast/utilities.go index c63ce7238c840..f9595e55065dc 100644 --- a/tsc/internal/ast/utilities.go +++ b/tsc/internal/ast/utilities.go @@ -2835,20 +2835,24 @@ func ForEachDynamicImportOrRequireCall( ) bool { isJavaScriptFile := IsInJSFile(file.AsNode()) lastIndex, size := findImportOrRequire(file.Text(), 0) + // The text search can find "import" or "require" in an argument as well as at the call, + // so GetNodeAtPosition may resolve multiple matches to the same AST node. + var lastNode *Node for lastIndex >= 0 { node := GetNodeAtPosition(file, lastIndex, isJavaScriptFile && includeTypeSpaceImports) + var argument *Expression if isJavaScriptFile && IsRequireCall(node, requireStringLiteralLikeArgument) { - if cb(node, node.Arguments()[0]) { - return true - } + argument = node.Arguments()[0] } else if IsImportCall(node) && len(node.Arguments()) > 0 && (!requireStringLiteralLikeArgument || IsStringLiteralLike(node.Arguments()[0])) { - if cb(node, node.Arguments()[0]) { - return true - } + argument = node.Arguments()[0] } else if includeTypeSpaceImports && IsLiteralImportTypeNode(node) { - if cb(node, node.AsImportTypeNode().Argument.AsLiteralTypeNode().Literal) { + argument = node.AsImportTypeNode().Argument.AsLiteralTypeNode().Literal + } + if argument != nil && node != lastNode { + if cb(node, argument) { return true } + lastNode = node } // skip past import/require lastIndex += size diff --git a/tsc/internal/fourslash/tests/getEditsForFileRename_dynamicImportTsExtension_test.go b/tsc/internal/fourslash/tests/getEditsForFileRename_dynamicImportTsExtension_test.go new file mode 100644 index 0000000000000..d343527b93c22 --- /dev/null +++ b/tsc/internal/fourslash/tests/getEditsForFileRename_dynamicImportTsExtension_test.go @@ -0,0 +1,33 @@ +package fourslash_test + +import ( + "testing" + + "github.com/microsoft/TypeScript/tsc/internal/fourslash" + "github.com/microsoft/TypeScript/tsc/internal/testutil" +) + +func TestGetEditsForFileRename_dynamicImportTsExtension(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + // The "import" prefix in "./imported.ts" is another match for the text scan and used to collect this node twice. + const content = `// @Filename: /tsconfig.json +{ + "compilerOptions": { + "module": "esnext", + "moduleResolution": "bundler", + "target": "es2022", + "allowImportingTsExtensions": true, + "noEmit": true + } +} +// @Filename: /imported.ts +export const value = 1; +// @Filename: /loads.ts +export const load = () => import("./imported.ts");` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyWillRenameFilesEdits(t, "/imported.ts", "/sub/moved.ts", map[string]string{ + "/loads.ts": `export const load = () => import("./sub/moved.ts");`, + }, nil /*preferences*/) +}