fix(ng-add): material version could not be determined (#12751)

Due to the fact that the CLI **only** installs `@angular/material` when running `ng add` and expects us to add the entries to the `package.json`, we cannot use the `VERSION` object from `@angular/material` because the Material package tries to `require` the CDK (which is not present at this point). This results in a runtime exception that will cause the `materialVersion` to be `null`.

In order to properly determine the Material version that comes with the `ng add` command, we should gracefully inspect the according `package.json` file of the `@angular/material` or `@angular/cdk` package.
This commit is contained in:
Paul Gschwendtner
2018-08-20 22:38:27 +02:00
committed by Jeremy Elbourn
parent b9651dfa4c
commit a027ae59c8
2 changed files with 10 additions and 7 deletions
+4 -4
View File
@@ -24,7 +24,7 @@ import {getProjectStyleFile} from '../utils/project-style-file';
import {addFontsToIndex} from './fonts/material-fonts';
import {Schema} from './schema';
import {addThemeToAppStyles} from './theming/theming';
import {materialVersion, requiredAngularVersion} from './version-names';
import {materialVersion, requiredAngularVersionRange} from './version-names';
/**
* Scaffolds the basics of a Angular Material application, this includes:
@@ -55,10 +55,10 @@ function addMaterialToPackageJson() {
// have the same version tag if possible.
const ngCoreVersionTag = getPackageVersionFromPackageJson(host, '@angular/core');
addPackageToPackageJson(host, 'dependencies', '@angular/cdk', materialVersion);
addPackageToPackageJson(host, 'dependencies', '@angular/material', materialVersion);
addPackageToPackageJson(host, 'dependencies', '@angular/cdk', `^${materialVersion}`);
addPackageToPackageJson(host, 'dependencies', '@angular/material', `^${materialVersion}`);
addPackageToPackageJson(host, 'dependencies', '@angular/animations',
ngCoreVersionTag || requiredAngularVersion);
ngCoreVersionTag || requiredAngularVersionRange);
context.addTask(new NodePackageInstallTask());
+6 -3
View File
@@ -11,13 +11,16 @@ export const materialVersion =
loadPackageVersionGracefully('@angular/cdk') ||
loadPackageVersionGracefully('@angular/material');
/** Angular version that is needed for the Material version that comes with the schematics. */
export const requiredAngularVersion = '0.0.0-NG';
/**
* Range of Angular versions that can be used together with the Angular Material version
* that provides these schematics.
*/
export const requiredAngularVersionRange = '0.0.0-NG';
/** Loads the full version from the given Angular package gracefully. */
function loadPackageVersionGracefully(packageName: string): string | null {
try {
return require(packageName).VERSION.full;
return require(`${packageName}/package.json`).version;
} catch {
return null;
}