Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/schematics/angular/utility/ast-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,14 @@ export function insertImport(
// if there are no imports or 'use strict' statement, insert import at beginning of file
const insertAtBeginning = allImports.length === 0 && useStrict.length === 0;
const separator = insertAtBeginning ? '' : `;${eol}`;
const escapedFileName = fileName
.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r');
const toInsert =
`${separator}import ${open}${importExpression}${close}` +
` from '${fileName}'${insertAtBeginning ? `;${eol}` : ''}`;
` from '${escapedFileName}'${insertAtBeginning ? `;${eol}` : ''}`;
Comment thread
herdiyana256 marked this conversation as resolved.

return insertAfterLastOccurrence(
allImports,
Expand Down
18 changes: 18 additions & 0 deletions packages/schematics/angular/utility/ast-utils_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -768,6 +768,24 @@ describe('ast utils', () => {

expect(result).toBe(fileContent);
});

it('should escape single quotes and backslashes in the module specifier', () => {
const fileContent = '';
const source = getTsSource(filePath, fileContent);
const change = insertImport(source, filePath, 'Component', "foo'bar\\baz");
const result = applyChanges(filePath, fileContent, [change]).trim();

expect(result).toBe("import { Component } from 'foo\\'bar\\\\baz';");
});

it('should escape newlines and carriage returns in the module specifier', () => {
const fileContent = '';
const source = getTsSource(filePath, fileContent);
const change = insertImport(source, filePath, 'Component', 'foo\nbar\rbaz');
const result = applyChanges(filePath, fileContent, [change]).trim();

expect(result).toBe(`import { Component } from 'foo\\nbar\\rbaz';`);
});
});

describe('hasTopLevelIdentifier', () => {
Expand Down