refactor(@angular/cli): remove deprecated --prod flag

BREAKING CHANGE:

Deprecated option `--prod` has been removed from all builders. `--configuration production`/`-c production` should be used instead if the default configuration of the builder is not configured to `production`.
This commit is contained in:
Alan Agius 2022-01-28 12:07:31 +01:00 committed by Douglas Parker
parent 69ecddaa7d
commit 2fc7c73d7e
9 changed files with 232 additions and 218 deletions

View File

@ -14,14 +14,9 @@
}
},
"configuration": {
"description": "One or more named builder configurations as a comma-separated list as specified in the \"configurations\" section of angular.json.\nThe builder uses the named configurations to run the given target.\nFor more information, see https://angular.io/guide/workspace-config#alternate-build-configurations.\nSetting this explicitly overrides the \"--prod\" flag.",
"description": "One or more named builder configurations as a comma-separated list as specified in the \"configurations\" section of angular.json.\nThe builder uses the named configurations to run the given target.\nFor more information, see https://angular.io/guide/workspace-config#alternate-build-configurations.",
"type": "string",
"aliases": ["c"]
},
"prod": {
"description": "Shorthand for \"--configuration=production\".\nSet the build configuration to the production target.\nBy default, the production target is set up in the workspace configuration such that all builds make use of bundling, limited tree-shaking, and also limited dead code elimination.",
"type": "boolean",
"x-deprecated": "Use `--configuration production` instead."
}
}
},

View File

@ -422,21 +422,6 @@ export abstract class ArchitectCommand<
} else {
project = commandOptions.project;
target = this.target;
if (commandOptions.prod) {
const defaultConfig =
project &&
target &&
this.workspace?.projects.get(project)?.targets.get(target)?.defaultConfiguration;
this.logger.warn(
defaultConfig === 'production'
? 'Option "--prod" is deprecated: No need to use this option as this builder defaults to configuration "production".'
: 'Option "--prod" is deprecated: Use "--configuration production" instead.',
);
// The --prod flag will always be the first configuration, available to be overwritten
// by following configurations.
configuration = 'production';
}
if (commandOptions.configuration) {
configuration = `${configuration ? `${configuration},` : ''}${
commandOptions.configuration

View File

@ -12,7 +12,7 @@ Run `ng generate component component-name` to generate a new component. You can
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
## Running unit tests

View File

@ -16,29 +16,37 @@ export default async function () {
// Add app routing.
// This is done automatically on a new app with --routing.
await writeFile(appRoutingModulePath, `
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
await writeFile(
appRoutingModulePath,
`
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [];
const routes: Routes = [];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
`);
await prependToFile('src/app/app.module.ts',
`import { AppRoutingModule } from './app-routing.module';`);
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
`,
);
await prependToFile(
'src/app/app.module.ts',
`import { AppRoutingModule } from './app-routing.module';`,
);
await replaceInFile('src/app/app.module.ts', `imports: [`, `imports: [ AppRoutingModule,`);
await appendToFile('src/app/app.component.html', '<router-outlet></router-outlet>');
const originalAppRoutingModule = await readFile(appRoutingModulePath);
// helper to replace loadChildren
const replaceLoadChildren = async (route: string) => {
const content = originalAppRoutingModule.replace('const routes: Routes = [];', `
const routes: Routes = [{ path: 'lazy', loadChildren: ${route} }];
`);
const content = originalAppRoutingModule.replace(
'const routes: Routes = [];',
`
const routes: Routes = [{ path: 'lazy', loadChildren: ${route} }];
`,
);
return writeFile(appRoutingModulePath, content);
};
@ -46,34 +54,41 @@ export default async function () {
// Add lazy route.
await ng('generate', 'module', 'lazy', '--routing');
await ng('generate', 'component', 'lazy/lazy-comp');
await replaceInFile('src/app/lazy/lazy-routing.module.ts', 'const routes: Routes = [];', `
import { LazyCompComponent } from './lazy-comp/lazy-comp.component';
const routes: Routes = [{ path: '', component: LazyCompComponent }];
`);
await replaceInFile(
'src/app/lazy/lazy-routing.module.ts',
'const routes: Routes = [];',
`
import { LazyCompComponent } from './lazy-comp/lazy-comp.component';
const routes: Routes = [{ path: '', component: LazyCompComponent }];
`,
);
// Add lazy route e2e
await writeFile('e2e/src/app.e2e-spec.ts', `
import { browser, logging, element, by } from 'protractor';
await writeFile(
'e2e/src/app.e2e-spec.ts',
`
import { browser, logging, element, by } from 'protractor';
describe('workspace-project App', () => {
it('should display lazy route', async () => {
await browser.get(browser.baseUrl + '/lazy');
expect(await element(by.css('app-lazy-comp p')).getText()).toEqual('lazy-comp works!');
});
describe('workspace-project App', () => {
it('should display lazy route', async () => {
await browser.get(browser.baseUrl + '/lazy');
expect(await element(by.css('app-lazy-comp p')).getText()).toEqual('lazy-comp works!');
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
}));
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
}));
});
});
});
`);
`,
);
// Convert the default config to use JIT and prod to just do AOT.
// This way we can use `ng e2e` to test JIT and `ng e2e --prod` to test AOT.
await updateJsonFile('angular.json', json => {
// This way we can use `ng e2e` to test JIT and `ng e2e --configuration=production` to test AOT.
await updateJsonFile('angular.json', (json) => {
const buildTarget = json['projects'][projectName]['architect']['build'];
buildTarget['options']['aot'] = true;
buildTarget['configurations']['development']['aot'] = false;

View File

@ -7,7 +7,7 @@ import { isPrereleaseCli, updateJsonFile } from '../../utils/project';
const snapshots = require('../../ng-snapshot/package.json');
export default async function () {
const tag = await isPrereleaseCli() ? '@next' : '';
const tag = (await isPrereleaseCli()) ? '@next' : '';
await ng('add', `@angular/material${tag}`, '--skip-confirmation');
const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots'];
@ -72,5 +72,5 @@ export default async function () {
`,
);
await ng('e2e', '--prod');
await ng('e2e', '--configuration=production');
}

View File

@ -8,17 +8,21 @@ import { wait } from '../../utils/utils';
const webpackGoodRegEx = / Compiled successfully./;
export default async function() {
export default async function () {
if (process.platform.startsWith('win')) {
return;
}
let error;
try {
await execAndWaitForOutputToMatch('ng', ['serve', '--prod'], webpackGoodRegEx);
await execAndWaitForOutputToMatch(
'ng',
['serve', '--configuration=production'],
webpackGoodRegEx,
);
await wait(4000);
// Should trigger a rebuild.
await appendToFile('src/environments/environment.prod.ts', `console.log('PROD');`);
await waitForAnyProcessOutputToMatch(webpackGoodRegEx, 45000);

View File

@ -3,159 +3,162 @@ import { installWorkspacePackages } from '../../utils/packages';
import { ng } from '../../utils/process';
import { updateJsonFile } from '../../utils/project';
export default function () {
return updateJsonFile('package.json', packageJson => {
export default async function () {
await updateJsonFile('package.json', (packageJson) => {
// Install ngrx
packageJson['dependencies']['@ngrx/effects'] = '^9.1.0';
packageJson['dependencies']['@ngrx/schematics'] = '^9.1.0';
packageJson['dependencies']['@ngrx/store'] = '^9.1.0';
packageJson['dependencies']['@ngrx/store-devtools'] = '^9.1.0';
})
.then(() => installWorkspacePackages())
// Create an app that uses ngrx decorators and has e2e tests.
.then(_ => writeMultipleFiles({
'./e2e/src/app.po.ts': `
import { browser, by, element } from 'protractor';
export class AppPage {
async navigateTo() { return browser.get('/'); }
getIncrementButton() { return element(by.buttonText('Increment')); }
getDecrementButton() { return element(by.buttonText('Decrement')); }
getResetButton() { return element(by.buttonText('Reset Counter')); }
async getCounter() { return element(by.xpath('/html/body/app-root/div/span')).getText(); }
}
`,
'./e2e/src/app.e2e-spec.ts': `
import { AppPage } from './app.po';
});
describe('workspace-project App', () => {
let page: AppPage;
await installWorkspacePackages();
beforeEach(() => {
page = new AppPage();
});
// Create an app that uses ngrx decorators and has e2e tests.
await writeMultipleFiles({
'./e2e/src/app.po.ts': `
import { browser, by, element } from 'protractor';
export class AppPage {
async navigateTo() { return browser.get('/'); }
getIncrementButton() { return element(by.buttonText('Increment')); }
getDecrementButton() { return element(by.buttonText('Decrement')); }
getResetButton() { return element(by.buttonText('Reset Counter')); }
async getCounter() { return element(by.xpath('/html/body/app-root/div/span')).getText(); }
}
`,
'./e2e/src/app.e2e-spec.ts': `
import { AppPage } from './app.po';
it('should operate counter', async () => {
await page.navigateTo();
await page.getIncrementButton().click();
await page.getIncrementButton().click();
expect(await page.getCounter()).toEqual('2');
await page.getDecrementButton().click();
expect(await page.getCounter()).toEqual('1');
await page.getResetButton().click();
expect(await page.getCounter()).toEqual('0');
});
describe('workspace-project App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
`,
'./src/app/app.component.ts': `
import { Component } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Observable } from 'rxjs';
import { INCREMENT, DECREMENT, RESET } from './counter.reducer';
interface AppState {
count: number;
it('should operate counter', async () => {
await page.navigateTo();
await page.getIncrementButton().click();
await page.getIncrementButton().click();
expect(await page.getCounter()).toEqual('2');
await page.getDecrementButton().click();
expect(await page.getCounter()).toEqual('1');
await page.getResetButton().click();
expect(await page.getCounter()).toEqual('0');
});
});
`,
'./src/app/app.component.ts': `
import { Component } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Observable } from 'rxjs';
import { INCREMENT, DECREMENT, RESET } from './counter.reducer';
interface AppState {
count: number;
}
@Component({
selector: 'app-root',
template: \`
<button (click)="increment()">Increment</button>
<div>Current Count: <span>{{ count$ | async }}</span></div>
<button (click)="decrement()">Decrement</button>
<button (click)="reset()">Reset Counter</button>
\`,
})
export class AppComponent {
count$: Observable<number>;
constructor(private store: Store<AppState>) {
this.count$ = store.pipe(select(state => state.count));
}
@Component({
selector: 'app-root',
template: \`
<button (click)="increment()">Increment</button>
<div>Current Count: <span>{{ count$ | async }}</span></div>
<button (click)="decrement()">Decrement</button>
<button (click)="reset()">Reset Counter</button>
\`,
})
export class AppComponent {
count$: Observable<number>;
constructor(private store: Store<AppState>) {
this.count$ = store.pipe(select(state => state.count));
}
increment() {
this.store.dispatch({ type: INCREMENT });
}
decrement() {
this.store.dispatch({ type: DECREMENT });
}
reset() {
this.store.dispatch({ type: RESET });
}
increment() {
this.store.dispatch({ type: INCREMENT });
}
`,
'./src/app/app.effects.ts': `
import { Injectable } from '@angular/core';
import { Actions, Effect } from '@ngrx/effects';
import { filter, map, tap } from 'rxjs/operators';
@Injectable()
export class AppEffects {
@Effect()
mapper$ = this.actions$.pipe(map(() => ({ type: 'ANOTHER'})), filter(() => false));
@Effect({ dispatch: false })
logger$ = this.actions$.pipe(tap(console.log));
constructor(private actions$: Actions) {}
decrement() {
this.store.dispatch({ type: DECREMENT });
}
`,
'./src/app/app.module.ts': `
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { StoreModule } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { environment } from '../environments/environment';
import { EffectsModule } from '@ngrx/effects';
import { AppEffects } from './app.effects';
import { counterReducer } from './counter.reducer';
reset() {
this.store.dispatch({ type: RESET });
}
}
`,
'./src/app/app.effects.ts': `
import { Injectable } from '@angular/core';
import { Actions, Effect } from '@ngrx/effects';
import { filter, map, tap } from 'rxjs/operators';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
StoreModule.forRoot({ count: counterReducer }),
!environment.production ? StoreDevtoolsModule.instrument() : [],
EffectsModule.forRoot([AppEffects])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
`,
'./src/app/counter.reducer.ts': `
import { Action } from '@ngrx/store';
@Injectable()
export class AppEffects {
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
export const RESET = 'RESET';
@Effect()
mapper$ = this.actions$.pipe(map(() => ({ type: 'ANOTHER'})), filter(() => false));
const initialState = 0;
@Effect({ dispatch: false })
logger$ = this.actions$.pipe(tap(console.log));
export function counterReducer(state: number = initialState, action: Action) {
switch (action.type) {
case INCREMENT:
return state + 1;
case DECREMENT:
return state - 1;
case RESET:
return 0;
default:
return state;
constructor(private actions$: Actions) {}
}
}
`,
}))
// Run the e2e tests against a prod build.
.then(() => ng('e2e', '--prod'));
'./src/app/app.module.ts': `
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { StoreModule } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { environment } from '../environments/environment';
import { EffectsModule } from '@ngrx/effects';
import { AppEffects } from './app.effects';
import { counterReducer } from './counter.reducer';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
StoreModule.forRoot({ count: counterReducer }),
!environment.production ? StoreDevtoolsModule.instrument() : [],
EffectsModule.forRoot([AppEffects])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
`,
'./src/app/counter.reducer.ts': `
import { Action } from '@ngrx/store';
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
export const RESET = 'RESET';
const initialState = 0;
export function counterReducer(state: number = initialState, action: Action) {
switch (action.type) {
case INCREMENT:
return state + 1;
case DECREMENT:
return state - 1;
case RESET:
return 0;
default:
return state;
}
}
`,
});
// Run the e2e tests against a production build.
await ng('e2e', '--configuration=production');
}

View File

@ -4,7 +4,10 @@ import { updateJsonFile } from '../../utils/project';
export default function () {
// Tests run in 'dev' environment by default.
return writeFile('src/app/environment.spec.ts', `
return (
writeFile(
'src/app/environment.spec.ts',
`
import { environment } from '../environments/environment';
describe('Test environment', () => {
@ -12,24 +15,30 @@ export default function () {
expect(environment.production).toBe(false);
});
});
`)
.then(() => ng('test', '--watch=false'))
.then(() => updateJsonFile('angular.json', configJson => {
const appArchitect = configJson.projects['test-project'].architect;
appArchitect.test.configurations = {
production: {
fileReplacements: [
{
src: 'src/environments/environment.ts',
replaceWith: 'src/environments/environment.prod.ts',
}
],
}
};
}))
`,
)
.then(() => ng('test', '--watch=false'))
.then(() =>
updateJsonFile('angular.json', (configJson) => {
const appArchitect = configJson.projects['test-project'].architect;
appArchitect.test.configurations = {
production: {
fileReplacements: [
{
src: 'src/environments/environment.ts',
replaceWith: 'src/environments/environment.prod.ts',
},
],
},
};
}),
)
// Tests can run in different environment.
.then(() => writeFile('src/app/environment.spec.ts', `
// Tests can run in different environment.
.then(() =>
writeFile(
'src/app/environment.spec.ts',
`
import { environment } from '../environments/environment';
describe('Test environment', () => {
@ -37,6 +46,9 @@ export default function () {
expect(environment.production).toBe(true);
});
});
`))
.then(() => ng('test', '--prod', '--watch=false'));
`,
),
)
.then(() => ng('test', '--configuration=production', '--watch=false'))
);
}

View File

@ -49,9 +49,9 @@ export default async function () {
await ng('generate', 'component', 'my-comp');
await ng('test', '--watch=false');
await ng('e2e');
await ng('e2e', '--prod');
await ng('e2e', '--configuration=production');
// Verify project now creates bundles
await noSilentNg('build', '--prod');
await noSilentNg('build', '--configuration=production');
await expectFileMatchToExist('dist/nine-project/', /main\.[0-9a-f]{16}\.js/);
}