diff --git a/packages/schematics/angular/utility/ast-utils.ts b/packages/schematics/angular/utility/ast-utils.ts index da7fbf8f526c..3324c5627cc1 100644 --- a/packages/schematics/angular/utility/ast-utils.ts +++ b/packages/schematics/angular/utility/ast-utils.ts @@ -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}` : ''}`; return insertAfterLastOccurrence( allImports, diff --git a/packages/schematics/angular/utility/ast-utils_spec.ts b/packages/schematics/angular/utility/ast-utils_spec.ts index c937d7124ebe..ead53d29d5b8 100644 --- a/packages/schematics/angular/utility/ast-utils_spec.ts +++ b/packages/schematics/angular/utility/ast-utils_spec.ts @@ -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', () => {