Skip to content

Commit f6740fe

Browse files
committed
[clang-format] Indent import statements in JavaScript.
[clang-format] Indent import statements in JavaScript. Take for example this piece of code found at <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import>. ``` for (const link of document.querySelectorAll("nav > a")) { link.addEventListener("click", e => { e.preventDefault(); import('/modules/my-module.js') .then(module => { module.loadPageInto(main); }) .catch(err => { main.textContent = err.message; }); }); } ``` Previously the import line would be unindented, looking like this. ``` for (const link of document.querySelectorAll("nav > a")) { link.addEventListener("click", e => { e.preventDefault(); import('/modules/my-module.js') .then(module => { module.loadPageInto(main); }) .catch(err => { main.textContent = err.message; }); }); } ``` Actually we were going to fix this along with fixing Verilog import statements. But the patch got too big. Reviewed By: MyDeveloperDay, curdeius Differential Revision: https://reviews.llvm.org/D121906
1 parent a114ec0 commit f6740fe

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

clang/lib/Format/UnwrappedLineFormatter.cpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1431,8 +1431,10 @@ void UnwrappedLineFormatter::formatFirstToken(
14311431
if (Newlines)
14321432
Indent = NewlineIndent;
14331433

1434-
// Preprocessor directives get indented before the hash only if specified
1435-
if (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
1434+
// Preprocessor directives get indented before the hash only if specified. In
1435+
// Javascript import statements are indented like normal statements.
1436+
if (!Style.isJavaScript() &&
1437+
Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
14361438
(Line.Type == LT_PreprocessorDirective ||
14371439
Line.Type == LT_ImportStatement))
14381440
Indent = 0;

clang/unittests/Format/FormatTestJS.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1875,6 +1875,11 @@ TEST_F(FormatTestJS, Modules) {
18751875
" myX} from 'm';");
18761876
verifyFormat("import * as lib from 'some/module.js';");
18771877
verifyFormat("var x = {import: 1};\nx.import = 2;");
1878+
// Ensure an import statement inside a block is at the correct level.
1879+
verifyFormat("function() {\n"
1880+
" var x;\n"
1881+
" import 'some/module.js';\n"
1882+
"}");
18781883

18791884
verifyFormat("export function fn() {\n"
18801885
" return 'fn';\n"

0 commit comments

Comments
 (0)