From f92321f51585a70cbb677624c121cb5b9e59f4bf Mon Sep 17 00:00:00 2001 From: Stephen Cavaliere Date: Sat, 4 Mar 2017 00:13:37 -0500 Subject: [PATCH] fix(@angular/cli): fix component not finding closest module fixes #5127 --- packages/@angular/cli/blueprints/component/index.ts | 3 +-- .../@angular/cli/utilities/find-parent-module.ts | 4 ++++ .../component/component-in-existing-module-dir.ts | 13 +++++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 tests/e2e/tests/generate/component/component-in-existing-module-dir.ts diff --git a/packages/@angular/cli/blueprints/component/index.ts b/packages/@angular/cli/blueprints/component/index.ts index ef5d9bcbd45c..2ef24c7c102e 100644 --- a/packages/@angular/cli/blueprints/component/index.ts +++ b/packages/@angular/cli/blueprints/component/index.ts @@ -95,8 +95,7 @@ export default Blueprint.extend({ } } else { try { - this.pathToModule = findParentModule( - this.project.root, appConfig.root, this.dynamicPath.dir); + this.pathToModule = findParentModule(this.project.root, appConfig.root, this.generatePath); } catch (e) { if (!options.skipImport) { throw `Error locating module for declaration\n\t${e}`; diff --git a/packages/@angular/cli/utilities/find-parent-module.ts b/packages/@angular/cli/utilities/find-parent-module.ts index 3236167121cf..61be86780b5e 100644 --- a/packages/@angular/cli/utilities/find-parent-module.ts +++ b/packages/@angular/cli/utilities/find-parent-module.ts @@ -13,6 +13,10 @@ export default function findParentModule( let pathToCheck = path.join(sourceRoot, currentDir); while (pathToCheck.length >= sourceRoot.length) { + if (!fs.existsSync(pathToCheck)) { + pathToCheck = path.dirname(pathToCheck); + continue; + } // TODO: refactor to not be based upon file name const files = fs.readdirSync(pathToCheck) .filter(fileName => !fileName.endsWith('routing.module.ts')) diff --git a/tests/e2e/tests/generate/component/component-in-existing-module-dir.ts b/tests/e2e/tests/generate/component/component-in-existing-module-dir.ts new file mode 100644 index 000000000000..073fb6d64a22 --- /dev/null +++ b/tests/e2e/tests/generate/component/component-in-existing-module-dir.ts @@ -0,0 +1,13 @@ +import { join } from 'path'; +import { ng } from '../../../utils/process'; +import { expectFileToMatch } from '../../../utils/fs'; + + +export default function () { + const modulePath = join('src', 'app', 'foo', 'foo.module.ts'); + + return Promise.resolve() + .then(() => ng('generate', 'module', 'foo')) + .then(() => ng('generate', 'component', 'foo')) + .then(() => expectFileToMatch(modulePath, /import { FooComponent } from '.\/foo.component'/)); +}