From 87fb244d163e4b93b5da1b2000b9239d28dccb8a Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Mon, 19 Sep 2022 09:14:35 +0000 Subject: [PATCH] feat(@schematics/angular): remove environment files in new applications This commit removes the usage of environment files and `fileReplacements` in new application projects. Previously, the environment files was used to distinguish between a prod build to invoke `enableProdMode`. The `enableProdMode` however needed only for the case of JIT mode in production mode, which is a rare case as JIT mode is recommanded to be used in production. In the CLI, calling `enableProdMode` is not needed as `ngDevMode` it's set using the minifier. --- .../src/builders/app-shell/app-shell_spec.ts | 8 -- .../builders/browser/specs/rebuild_spec.ts | 7 -- .../specs/unused-files-warning_spec.ts | 12 +-- .../browser/specs/vendor-source-map_spec.ts | 1 - .../builders/browser/specs/web-worker_spec.ts | 3 - .../test/hello-world-app/angular.json | 6 -- .../src/environments/environment.prod.ts | 11 --- .../src/environments/environment.ts | 16 ---- .../test/hello-world-app/src/main.server.ts | 7 -- .../test/hello-world-app/src/main.ts | 6 -- .../src/environments/environment.prod.ts | 11 --- .../src/environments/environment.ts | 16 ---- .../test/angular-app/src/main.ts | 7 -- .../environments/environment.prod.ts.template | 3 - .../src/environments/environment.ts.template | 16 ---- .../application/files/src/main.ts.template | 8 +- .../schematics/angular/application/index.ts | 6 -- .../angular/application/index_spec.ts | 12 +-- .../angular/service-worker/index.ts | 44 ++++------ .../angular/service-worker/index_spec.ts | 86 +------------------ .../src/__main@stripTsExtension__.ts.template | 9 +- .../angular/universal/index_spec.ts | 13 --- .../schematics/angular/utility/ast-utils.ts | 45 ---------- .../legacy-cli/e2e/tests/basic/environment.ts | 22 ----- tests/legacy-cli/e2e/tests/basic/rebuild.ts | 7 -- .../e2e/tests/build/rebuild-replacements.ts | 25 +++++- .../e2e/tests/i18n/ivy-localize-app-shell.ts | 14 --- tests/legacy-cli/e2e/tests/i18n/setup.ts | 6 -- .../e2e/tests/misc/third-party-decorators.ts | 3 +- .../e2e/tests/test/test-environment.ts | 26 ++++-- 30 files changed, 68 insertions(+), 388 deletions(-) delete mode 100644 packages/angular_devkit/build_angular/test/hello-world-app/src/environments/environment.prod.ts delete mode 100644 packages/angular_devkit/build_angular/test/hello-world-app/src/environments/environment.ts delete mode 100644 packages/angular_devkit/build_webpack/test/angular-app/src/environments/environment.prod.ts delete mode 100644 packages/angular_devkit/build_webpack/test/angular-app/src/environments/environment.ts delete mode 100644 packages/schematics/angular/application/files/src/environments/environment.prod.ts.template delete mode 100644 packages/schematics/angular/application/files/src/environments/environment.ts.template delete mode 100644 tests/legacy-cli/e2e/tests/basic/environment.ts diff --git a/packages/angular_devkit/build_angular/src/builders/app-shell/app-shell_spec.ts b/packages/angular_devkit/build_angular/src/builders/app-shell/app-shell_spec.ts index 8b2ba1734e64..e192d7387a29 100644 --- a/packages/angular_devkit/build_angular/src/builders/app-shell/app-shell_spec.ts +++ b/packages/angular_devkit/build_angular/src/builders/app-shell/app-shell_spec.ts @@ -51,7 +51,6 @@ describe('AppShell Builder', () => { import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; - import { environment } from '../environments/environment'; import { RouterModule } from '@angular/router'; @NgModule({ @@ -91,15 +90,8 @@ describe('AppShell Builder', () => { export class AppServerModule {} `, 'src/main.ts': ` - import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; - import { AppModule } from './app/app.module'; - import { environment } from './environments/environment'; - - if (environment.production) { - enableProdMode(); - } document.addEventListener('DOMContentLoaded', () => { platformBrowserDynamic().bootstrapModule(AppModule) diff --git a/packages/angular_devkit/build_angular/src/builders/browser/specs/rebuild_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/specs/rebuild_spec.ts index 1146d0a036a4..3fd1698e08d2 100644 --- a/packages/angular_devkit/build_angular/src/builders/browser/specs/rebuild_spec.ts +++ b/packages/angular_devkit/build_angular/src/builders/browser/specs/rebuild_spec.ts @@ -55,15 +55,8 @@ describe('Browser Builder rebuilds', () => { export let X = '$$_E2E_GOLDEN_VALUE_2'; `, 'src/main.ts': ` - import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; - import { AppModule } from './app/app.module'; - import { environment } from './environments/environment'; - - if (environment.production) { - enableProdMode(); - } platformBrowserDynamic().bootstrapModule(AppModule); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/specs/unused-files-warning_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/specs/unused-files-warning_spec.ts index bb30ba52de09..5ff6302007f5 100644 --- a/packages/angular_devkit/build_angular/src/builders/browser/specs/unused-files-warning_spec.ts +++ b/packages/angular_devkit/build_angular/src/builders/browser/specs/unused-files-warning_spec.ts @@ -38,11 +38,11 @@ describe('Browser Builder unused files warnings', () => { }); it('should show warning when some files are unused', async () => { - host.replaceInFile( - 'src/tsconfig.app.json', - '"main.ts"', - '"main.ts", "environments/environment.prod.ts"', - ); + host.writeMultipleFiles({ + 'src/unused-file.ts': `export const unused = '1';`, + }); + + host.replaceInFile('src/tsconfig.app.json', '"main.ts"', '"main.ts", "unused-file.ts"'); const logger = new logging.Logger(''); const logs: string[] = []; @@ -51,7 +51,7 @@ describe('Browser Builder unused files warnings', () => { const run = await architect.scheduleTarget(targetSpec, undefined, { logger }); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); - expect(logs.join().includes(`environment.prod.ts ${warningMessageSuffix}`)).toBe(true); + expect(logs.join().includes(`unused-file.ts ${warningMessageSuffix}`)).toBe(true); await run.stop(); }); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/specs/vendor-source-map_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/specs/vendor-source-map_spec.ts index 4087e97ac9e4..6774ea793dcd 100644 --- a/packages/angular_devkit/build_angular/src/builders/browser/specs/vendor-source-map_spec.ts +++ b/packages/angular_devkit/build_angular/src/builders/browser/specs/vendor-source-map_spec.ts @@ -107,7 +107,6 @@ describe('Identifying third-party code in source maps', () => { expect(mainMap.sources.filter((_, i) => !mainMap[IGNORE_LIST].includes(i))).toEqual([ './src/app/app.component.ts', './src/app/app.module.ts', - './src/environments/environment.ts', './src/main.ts', ]); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/specs/web-worker_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/specs/web-worker_spec.ts index 8dd061cbcdda..489e1a392aee 100644 --- a/packages/angular_devkit/build_angular/src/builders/browser/specs/web-worker_spec.ts +++ b/packages/angular_devkit/build_angular/src/builders/browser/specs/web-worker_spec.ts @@ -37,11 +37,8 @@ describe('Browser Builder Web Worker support', () => { }); `, 'src/main.ts': ` - import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; - import { environment } from './environments/environment'; - if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule).catch(err => console.error(err)); const worker = new Worker(new URL('./app/app.worker', import.meta.url), { type: 'module' }); diff --git a/packages/angular_devkit/build_angular/test/hello-world-app/angular.json b/packages/angular_devkit/build_angular/test/hello-world-app/angular.json index 0200444814cc..33ff51506916 100644 --- a/packages/angular_devkit/build_angular/test/hello-world-app/angular.json +++ b/packages/angular_devkit/build_angular/test/hello-world-app/angular.json @@ -43,12 +43,6 @@ }, "configurations": { "production": { - "fileReplacements": [ - { - "replace": "src/environments/environment.ts", - "with": "src/environments/environment.prod.ts" - } - ], "optimization": true, "outputHashing": "all", "sourceMap": false, diff --git a/packages/angular_devkit/build_angular/test/hello-world-app/src/environments/environment.prod.ts b/packages/angular_devkit/build_angular/test/hello-world-app/src/environments/environment.prod.ts deleted file mode 100644 index e0818f2e9056..000000000000 --- a/packages/angular_devkit/build_angular/test/hello-world-app/src/environments/environment.prod.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * @license - * Copyright Google LLC All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -export const environment = { - production: true, -}; diff --git a/packages/angular_devkit/build_angular/test/hello-world-app/src/environments/environment.ts b/packages/angular_devkit/build_angular/test/hello-world-app/src/environments/environment.ts deleted file mode 100644 index 4d557376ecf6..000000000000 --- a/packages/angular_devkit/build_angular/test/hello-world-app/src/environments/environment.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * @license - * Copyright Google LLC All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -// The file contents for the current environment will overwrite these during build. -// The build system defaults to the dev environment which uses `environment.ts`, but if you do -// `ng build --env=prod` then `environment.prod.ts` will be used instead. -// The list of which env maps to which file can be found in `angular.json`. - -export const environment = { - production: false, -}; diff --git a/packages/angular_devkit/build_angular/test/hello-world-app/src/main.server.ts b/packages/angular_devkit/build_angular/test/hello-world-app/src/main.server.ts index 97e03b7b47fb..403a842a0e08 100644 --- a/packages/angular_devkit/build_angular/test/hello-world-app/src/main.server.ts +++ b/packages/angular_devkit/build_angular/test/hello-world-app/src/main.server.ts @@ -7,13 +7,6 @@ */ import '@angular/localize/init'; -import { enableProdMode } from '@angular/core'; - -import { environment } from './environments/environment'; - -if (environment.production) { - enableProdMode(); -} export { AppServerModule } from './app/app.server.module'; export { renderModule } from '@angular/platform-server'; diff --git a/packages/angular_devkit/build_angular/test/hello-world-app/src/main.ts b/packages/angular_devkit/build_angular/test/hello-world-app/src/main.ts index fdde6bed1f3f..2a16fe2683e5 100644 --- a/packages/angular_devkit/build_angular/test/hello-world-app/src/main.ts +++ b/packages/angular_devkit/build_angular/test/hello-world-app/src/main.ts @@ -6,15 +6,9 @@ * found in the LICENSE file at https://angular.io/license */ -import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; -import { environment } from './environments/environment'; - -if (environment.production) { - enableProdMode(); -} platformBrowserDynamic() .bootstrapModule(AppModule) diff --git a/packages/angular_devkit/build_webpack/test/angular-app/src/environments/environment.prod.ts b/packages/angular_devkit/build_webpack/test/angular-app/src/environments/environment.prod.ts deleted file mode 100644 index e0818f2e9056..000000000000 --- a/packages/angular_devkit/build_webpack/test/angular-app/src/environments/environment.prod.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * @license - * Copyright Google LLC All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -export const environment = { - production: true, -}; diff --git a/packages/angular_devkit/build_webpack/test/angular-app/src/environments/environment.ts b/packages/angular_devkit/build_webpack/test/angular-app/src/environments/environment.ts deleted file mode 100644 index a922b2b6e660..000000000000 --- a/packages/angular_devkit/build_webpack/test/angular-app/src/environments/environment.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * @license - * Copyright Google LLC All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -// The file contents for the current environment will overwrite these during build. -// The build system defaults to the dev environment which uses `environment.ts`, but if you do -// `ng build --env=prod` then `environment.prod.ts` will be used instead. -// The list of which env maps to which file can be found in `.angular-cli.json`. - -export const environment = { - production: false, -}; diff --git a/packages/angular_devkit/build_webpack/test/angular-app/src/main.ts b/packages/angular_devkit/build_webpack/test/angular-app/src/main.ts index d591155b22cd..8fd2558a6c7b 100644 --- a/packages/angular_devkit/build_webpack/test/angular-app/src/main.ts +++ b/packages/angular_devkit/build_webpack/test/angular-app/src/main.ts @@ -6,15 +6,8 @@ * found in the LICENSE file at https://angular.io/license */ -import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; - import { AppModule } from './app/app.module'; -import { environment } from './environments/environment'; - -if (environment.production) { - enableProdMode(); -} platformBrowserDynamic() .bootstrapModule(AppModule) diff --git a/packages/schematics/angular/application/files/src/environments/environment.prod.ts.template b/packages/schematics/angular/application/files/src/environments/environment.prod.ts.template deleted file mode 100644 index 3612073bc31c..000000000000 --- a/packages/schematics/angular/application/files/src/environments/environment.prod.ts.template +++ /dev/null @@ -1,3 +0,0 @@ -export const environment = { - production: true -}; diff --git a/packages/schematics/angular/application/files/src/environments/environment.ts.template b/packages/schematics/angular/application/files/src/environments/environment.ts.template deleted file mode 100644 index f56ff47022c7..000000000000 --- a/packages/schematics/angular/application/files/src/environments/environment.ts.template +++ /dev/null @@ -1,16 +0,0 @@ -// This file can be replaced during build by using the `fileReplacements` array. -// `ng build` replaces `environment.ts` with `environment.prod.ts`. -// The list of file replacements can be found in `angular.json`. - -export const environment = { - production: false -}; - -/* - * For easier debugging in development mode, you can import the following file - * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. - * - * This import should be commented out in production mode because it will have a negative impact - * on performance if an error is thrown. - */ -// import 'zone.js/plugins/zone-error'; // Included with Angular CLI. diff --git a/packages/schematics/angular/application/files/src/main.ts.template b/packages/schematics/angular/application/files/src/main.ts.template index 3d492bb9626b..9026ef6dd27b 100644 --- a/packages/schematics/angular/application/files/src/main.ts.template +++ b/packages/schematics/angular/application/files/src/main.ts.template @@ -1,12 +1,8 @@ -import { enableProdMode<% if(!!viewEncapsulation) { %>, ViewEncapsulation<% }%> } from '@angular/core'; +import { <% if(!!viewEncapsulation) { %>ViewEncapsulation<% }%> } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; -import { environment } from './environments/environment'; -if (environment.production) { - enableProdMode(); -} <% if(!!viewEncapsulation) { %> platformBrowserDynamic().bootstrapModule(AppModule, { defaultEncapsulation: ViewEncapsulation.<%= viewEncapsulation %> @@ -15,4 +11,4 @@ platformBrowserDynamic().bootstrapModule(AppModule, { <% } else { %> platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.error(err)); -<% } %> \ No newline at end of file +<% } %> diff --git a/packages/schematics/angular/application/index.ts b/packages/schematics/angular/application/index.ts index 88485f9cc3ff..2c8cbcdf0c20 100644 --- a/packages/schematics/angular/application/index.ts +++ b/packages/schematics/angular/application/index.ts @@ -168,12 +168,6 @@ function addAppToWorkspaceFile( configurations: { production: { budgets, - fileReplacements: [ - { - replace: `${sourceRoot}/environments/environment.ts`, - with: `${sourceRoot}/environments/environment.prod.ts`, - }, - ], outputHashing: 'all', }, development: { diff --git a/packages/schematics/angular/application/index_spec.ts b/packages/schematics/angular/application/index_spec.ts index 0e1bfc6f0665..83b0c257dc1c 100644 --- a/packages/schematics/angular/application/index_spec.ts +++ b/packages/schematics/angular/application/index_spec.ts @@ -55,8 +55,6 @@ describe('Application Schematic', () => { '/projects/foo/karma.conf.js', '/projects/foo/tsconfig.app.json', '/projects/foo/tsconfig.spec.json', - '/projects/foo/src/environments/environment.ts', - '/projects/foo/src/environments/environment.prod.ts', '/projects/foo/src/favicon.ico', '/projects/foo/src/index.html', '/projects/foo/src/main.ts', @@ -149,7 +147,7 @@ describe('Application Schematic', () => { const path = '/projects/foo/src/main.ts'; const content = tree.readContent(path); expect(content).toContain('defaultEncapsulation: ViewEncapsulation.ShadowDom'); - expect(content).toContain(`import { enableProdMode, ViewEncapsulation } from '@angular/core'`); + expect(content).toContain(`import { ViewEncapsulation } from '@angular/core'`); }); it('should set the right paths in the tsconfig.app.json', async () => { @@ -265,8 +263,6 @@ describe('Application Schematic', () => { expect(files).toEqual( jasmine.arrayContaining([ '/projects/foo/tsconfig.app.json', - '/projects/foo/src/environments/environment.ts', - '/projects/foo/src/environments/environment.prod.ts', '/projects/foo/src/favicon.ico', '/projects/foo/src/index.html', '/projects/foo/src/main.ts', @@ -295,8 +291,6 @@ describe('Application Schematic', () => { expect(files).toEqual( jasmine.arrayContaining([ '/projects/foo/tsconfig.app.json', - '/projects/foo/src/environments/environment.ts', - '/projects/foo/src/environments/environment.prod.ts', '/projects/foo/src/favicon.ico', '/projects/foo/src/index.html', '/projects/foo/src/main.ts', @@ -326,8 +320,6 @@ describe('Application Schematic', () => { expect(files).toEqual( jasmine.arrayContaining([ '/projects/foo/tsconfig.app.json', - '/projects/foo/src/environments/environment.ts', - '/projects/foo/src/environments/environment.prod.ts', '/projects/foo/src/favicon.ico', '/projects/foo/src/index.html', '/projects/foo/src/main.ts', @@ -408,8 +400,6 @@ describe('Application Schematic', () => { '/karma.conf.js', '/tsconfig.app.json', '/tsconfig.spec.json', - '/src/environments/environment.ts', - '/src/environments/environment.prod.ts', '/src/favicon.ico', '/src/index.html', '/src/main.ts', diff --git a/packages/schematics/angular/service-worker/index.ts b/packages/schematics/angular/service-worker/index.ts index 765bad7c4f9d..a5acad480b5c 100644 --- a/packages/schematics/angular/service-worker/index.ts +++ b/packages/schematics/angular/service-worker/index.ts @@ -22,12 +22,7 @@ import { import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks'; import * as ts from '../third_party/github.com/Microsoft/TypeScript/lib/typescript'; import { readWorkspace, writeWorkspace } from '../utility'; -import { - addSymbolToNgModuleMetadata, - getEnvironmentExportName, - insertImport, - isImported, -} from '../utility/ast-utils'; +import { addSymbolToNgModuleMetadata, insertImport } from '../utility/ast-utils'; import { applyToUpdateRecorder } from '../utility/change'; import { addPackageJsonDependency, getPackageJsonDependency } from '../utility/dependencies'; import { getAppModulePath } from '../utility/ng-ast-utils'; @@ -61,12 +56,15 @@ function updateAppModule(mainPath: string): Rule { const modulePath = getAppModulePath(host, mainPath); context.logger.debug(`module path: ${modulePath}`); - // add import - let moduleSource = getTsSourceFile(host, modulePath); - let importModule = 'ServiceWorkerModule'; - let importPath = '@angular/service-worker'; - if (!isImported(moduleSource, importModule, importPath)) { - const change = insertImport(moduleSource, modulePath, importModule, importPath); + // add service-worker import + { + const moduleSource = getTsSourceFile(host, modulePath); + const change = insertImport( + moduleSource, + modulePath, + 'ServiceWorkerModule', + '@angular/service-worker', + ); if (change) { const recorder = host.beginUpdate(modulePath); applyToUpdateRecorder(recorder, [change]); @@ -74,20 +72,10 @@ function updateAppModule(mainPath: string): Rule { } } - // add import for environments - // import { environment } from '../environments/environment'; - moduleSource = getTsSourceFile(host, modulePath); - const environmentExportName = getEnvironmentExportName(moduleSource); - // if environemnt import already exists then use the found one - // otherwise use the default name - importModule = environmentExportName || 'environment'; - // TODO: dynamically find environments relative path - importPath = '../environments/environment'; - - if (!environmentExportName) { - // if environment import was not found then insert the new one - // with default path and default export name - const change = insertImport(moduleSource, modulePath, importModule, importPath); + // add `isDevMode` import + { + const moduleSource = getTsSourceFile(host, modulePath); + const change = insertImport(moduleSource, modulePath, 'isDevMode', '@angular/core'); if (change) { const recorder = host.beginUpdate(modulePath); applyToUpdateRecorder(recorder, [change]); @@ -98,13 +86,13 @@ function updateAppModule(mainPath: string): Rule { // register SW in application module const importText = tags.stripIndent` ServiceWorkerModule.register('ngsw-worker.js', { - enabled: ${importModule}.production, + enabled: !isDevMode(), // Register the ServiceWorker as soon as the application is stable // or after 30 seconds (whichever comes first). registrationStrategy: 'registerWhenStable:30000' }) `; - moduleSource = getTsSourceFile(host, modulePath); + const moduleSource = getTsSourceFile(host, modulePath); const metadataChanges = addSymbolToNgModuleMetadata( moduleSource, modulePath, diff --git a/packages/schematics/angular/service-worker/index_spec.ts b/packages/schematics/angular/service-worker/index_spec.ts index aa16cd4c2246..48c088ed897a 100644 --- a/packages/schematics/angular/service-worker/index_spec.ts +++ b/packages/schematics/angular/service-worker/index_spec.ts @@ -73,14 +73,6 @@ describe('Service Worker Schematic', () => { expect(pkgText).toMatch(/import \{ ServiceWorkerModule \} from '@angular\/service-worker'/); }); - it('should import environment', async () => { - const tree = await schematicRunner - .runSchematicAsync('service-worker', defaultOptions, appTree) - .toPromise(); - const pkgText = tree.readContent('/projects/bar/src/app/app.module.ts'); - expect(pkgText).toMatch(/import \{ environment \} from '\.\.\/environments\/environment'/); - }); - it('should add the SW import to the NgModule imports', async () => { const tree = await schematicRunner .runSchematicAsync('service-worker', defaultOptions, appTree) @@ -89,83 +81,7 @@ describe('Service Worker Schematic', () => { expect(pkgText).toMatch( new RegExp( "(\\s+)ServiceWorkerModule\\.register\\('ngsw-worker\\.js', \\{\\n" + - '\\1 enabled: environment\\.production,\\n' + - '\\1 // Register the ServiceWorker as soon as the application is stable\\n' + - '\\1 // or after 30 seconds \\(whichever comes first\\)\\.\\n' + - "\\1 registrationStrategy: 'registerWhenStable:30000'\\n" + - '\\1}\\)', - ), - ); - }); - - it('should add the SW import to the NgModule imports with aliased environment', async () => { - const moduleContent = ` - import { BrowserModule } from '@angular/platform-browser'; - import { NgModule } from '@angular/core'; - - import { AppComponent } from './app.component'; - import { environment as env } from '../environments/environment'; - - @NgModule({ - declarations: [ - AppComponent - ], - imports: [ - BrowserModule - ], - bootstrap: [AppComponent] - }) - export class AppModule {} - `; - - appTree.overwrite('/projects/bar/src/app/app.module.ts', moduleContent); - - const tree = await schematicRunner - .runSchematicAsync('service-worker', defaultOptions, appTree) - .toPromise(); - const pkgText = tree.readContent('/projects/bar/src/app/app.module.ts'); - expect(pkgText).toMatch( - new RegExp( - "(\\s+)ServiceWorkerModule\\.register\\('ngsw-worker\\.js', \\{\\n" + - '\\1 enabled: env\\.production,\\n' + - '\\1 // Register the ServiceWorker as soon as the application is stable\\n' + - '\\1 // or after 30 seconds \\(whichever comes first\\)\\.\\n' + - "\\1 registrationStrategy: 'registerWhenStable:30000'\\n" + - '\\1}\\)', - ), - ); - }); - - it('should add the SW import to the NgModule imports with existing environment', async () => { - const moduleContent = ` - import { BrowserModule } from '@angular/platform-browser'; - import { NgModule } from '@angular/core'; - - import { AppComponent } from './app.component'; - import { environment } from '../environments/environment'; - - @NgModule({ - declarations: [ - AppComponent - ], - imports: [ - BrowserModule - ], - bootstrap: [AppComponent] - }) - export class AppModule {} - `; - - appTree.overwrite('/projects/bar/src/app/app.module.ts', moduleContent); - - const tree = await schematicRunner - .runSchematicAsync('service-worker', defaultOptions, appTree) - .toPromise(); - const pkgText = tree.readContent('/projects/bar/src/app/app.module.ts'); - expect(pkgText).toMatch( - new RegExp( - "(\\s+)ServiceWorkerModule\\.register\\('ngsw-worker\\.js', \\{\\n" + - '\\1 enabled: environment\\.production,\\n' + + '\\1 enabled: !isDevMode\\(\\),\\n' + '\\1 // Register the ServiceWorker as soon as the application is stable\\n' + '\\1 // or after 30 seconds \\(whichever comes first\\)\\.\\n' + "\\1 registrationStrategy: 'registerWhenStable:30000'\\n" + diff --git a/packages/schematics/angular/universal/files/src/__main@stripTsExtension__.ts.template b/packages/schematics/angular/universal/files/src/__main@stripTsExtension__.ts.template index 53e6ea3bb6e7..56368946064a 100644 --- a/packages/schematics/angular/universal/files/src/__main@stripTsExtension__.ts.template +++ b/packages/schematics/angular/universal/files/src/__main@stripTsExtension__.ts.template @@ -12,13 +12,6 @@ import '@angular/platform-server/init'; */ import '@angular/localize/init'; -<% } %>import { enableProdMode } from '@angular/core'; - -import { environment } from './environments/environment'; - -if (environment.production) { - enableProdMode(); -} - +<% } %> export { <%= rootModuleClassName %> } from './app/<%= stripTsExtension(rootModuleFileName) %>'; export { renderModule } from '@angular/platform-server'; diff --git a/packages/schematics/angular/universal/index_spec.ts b/packages/schematics/angular/universal/index_spec.ts index a9e64dc40be3..85a8b5bfa658 100644 --- a/packages/schematics/angular/universal/index_spec.ts +++ b/packages/schematics/angular/universal/index_spec.ts @@ -149,14 +149,6 @@ describe('Universal Schematic', () => { expect(opts.outputPath).toEqual('dist/bar/server'); expect(opts.main).toEqual('projects/bar/src/main.server.ts'); expect(opts.tsConfig).toEqual('projects/bar/tsconfig.server.json'); - const configurations = targets.server.configurations; - expect(configurations.production.fileReplacements.length).toEqual(1); - expect(configurations.production.fileReplacements[0].replace).toEqual( - 'projects/bar/src/environments/environment.ts', - ); - expect(configurations.production.fileReplacements[0].with).toEqual( - 'projects/bar/src/environments/environment.prod.ts', - ); }); it('should update workspace with a build target outputPath', async () => { @@ -193,16 +185,11 @@ describe('Universal Schematic', () => { appTree.overwrite( filePath, ` - import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; import { hmrBootstrap } from './hmr'; - if (environment.production) { - enableProdMode(); - } - const bootstrap = () => platformBrowserDynamic().bootstrapModule(AppModule); if (!hmrBootstrap) { diff --git a/packages/schematics/angular/utility/ast-utils.ts b/packages/schematics/angular/utility/ast-utils.ts index 56bde71bc187..ecb6f6d36f7c 100644 --- a/packages/schematics/angular/utility/ast-utils.ts +++ b/packages/schematics/angular/utility/ast-utils.ts @@ -553,51 +553,6 @@ export function isImported( return matchingNodes.length > 0; } -/** - * This function returns the name of the environment export - * whether this export is aliased or not. If the environment file - * is not imported, then it will return `null`. - */ -export function getEnvironmentExportName(source: ts.SourceFile): string | null { - // Initial value is `null` as we don't know yet if the user - // has imported `environment` into the root module or not. - let environmentExportName: string | null = null; - - const allNodes = getSourceNodes(source); - - allNodes - .filter(ts.isImportDeclaration) - .filter( - (declaration) => - declaration.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral && - declaration.importClause !== undefined, - ) - .map((declaration) => - // If `importClause` property is defined then the first - // child will be `NamedImports` object (or `namedBindings`). - (declaration.importClause as ts.ImportClause).getChildAt(0), - ) - // Find those `NamedImports` object that contains `environment` keyword - // in its text. E.g. `{ environment as env }`. - .filter(ts.isNamedImports) - .filter((namedImports) => namedImports.getText().includes('environment')) - .forEach((namedImports) => { - for (const specifier of namedImports.elements) { - // `propertyName` is defined if the specifier - // has an aliased import. - const name = specifier.propertyName || specifier.name; - - // Find specifier that contains `environment` keyword in its text. - // Whether it's `environment` or `environment as env`. - if (name.text.includes('environment')) { - environmentExportName = specifier.name.text; - } - } - }); - - return environmentExportName; -} - /** * Returns the RouterModule declaration from NgModule metadata, if any. */ diff --git a/tests/legacy-cli/e2e/tests/basic/environment.ts b/tests/legacy-cli/e2e/tests/basic/environment.ts deleted file mode 100644 index 5f376f8cc3db..000000000000 --- a/tests/legacy-cli/e2e/tests/basic/environment.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { expectFileToMatch } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; - -export default async function () { - // Try a prod build. - await updateJsonFile('angular.json', (configJson) => { - const appArchitect = configJson.projects['test-project'].architect; - appArchitect.build.configurations['prod-env'] = { - ...appArchitect.build.configurations['development'], - fileReplacements: [ - { - src: 'src/environments/environment.ts', - replaceWith: 'src/environments/environment.prod.ts', - }, - ], - }; - }); - - await ng('build', '--configuration=prod-env'); - await expectFileToMatch('dist/test-project/main.js', /production:\s*true/); -} diff --git a/tests/legacy-cli/e2e/tests/basic/rebuild.ts b/tests/legacy-cli/e2e/tests/basic/rebuild.ts index 8b507f6a19bd..2506f2ac0f61 100644 --- a/tests/legacy-cli/e2e/tests/basic/rebuild.ts +++ b/tests/legacy-cli/e2e/tests/basic/rebuild.ts @@ -73,15 +73,8 @@ export default async function () { export let X = '$$_E2E_GOLDEN_VALUE_2'; `, 'src/main.ts': ` - import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; - import { AppModule } from './app/app.module'; - import { environment } from './environments/environment'; - - if (environment.production) { - enableProdMode(); - } platformBrowserDynamic().bootstrapModule(AppModule); diff --git a/tests/legacy-cli/e2e/tests/build/rebuild-replacements.ts b/tests/legacy-cli/e2e/tests/build/rebuild-replacements.ts index f5c2b978ef84..f7d4c59bd66a 100644 --- a/tests/legacy-cli/e2e/tests/build/rebuild-replacements.ts +++ b/tests/legacy-cli/e2e/tests/build/rebuild-replacements.ts @@ -1,6 +1,6 @@ -import { appendToFile } from '../../utils/fs'; +import { appendToFile, createDir, writeMultipleFiles } from '../../utils/fs'; import { killAllProcesses, waitForAnyProcessOutputToMatch } from '../../utils/process'; -import { ngServe } from '../../utils/project'; +import { ngServe, updateJsonFile } from '../../utils/project'; const webpackGoodRegEx = / Compiled successfully./; @@ -9,7 +9,28 @@ export default async function () { return; } + await createDir('src/environments'); + try { + await writeMultipleFiles({ + 'src/environments/environment.ts': `export const env = 'dev';`, + 'src/environments/environment.prod.ts': `export const env = 'prod';`, + 'src/main.ts': ` + import { env } from 'environments/environment'; + console.log(env); + `, + }); + + await updateJsonFile('angular.json', (workspaceJson) => { + const appArchitect = workspaceJson.projects['test-project'].architect; + appArchitect.build.configurations.production.fileReplacements = [ + { + replace: 'src/environments/environment.ts', + with: 'src/environments/environment.prod.ts', + }, + ]; + }); + await ngServe('--configuration=production'); // Should trigger a rebuild. diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-app-shell.ts b/tests/legacy-cli/e2e/tests/i18n/ivy-localize-app-shell.ts index a0f828e8c800..9dac69df0190 100644 --- a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-app-shell.ts +++ b/tests/legacy-cli/e2e/tests/i18n/ivy-localize-app-shell.ts @@ -54,20 +54,6 @@ export default async function () { buildOptions.optimization = true; buildOptions.buildOptimizer = true; buildOptions.aot = true; - buildOptions.fileReplacements = [ - { - replace: 'src/environments/environment.ts', - with: 'src/environments/environment.prod.ts', - }, - ]; - - serverOptions.optimization = true; - serverOptions.fileReplacements = [ - { - replace: 'src/environments/environment.ts', - with: 'src/environments/environment.prod.ts', - }, - ]; // Enable localization for all locales buildOptions.localize = true; diff --git a/tests/legacy-cli/e2e/tests/i18n/setup.ts b/tests/legacy-cli/e2e/tests/i18n/setup.ts index 00279b6910bf..90e5f93e4c48 100644 --- a/tests/legacy-cli/e2e/tests/i18n/setup.ts +++ b/tests/legacy-cli/e2e/tests/i18n/setup.ts @@ -216,12 +216,6 @@ export async function setupI18nConfig() { appArchitect['build'].options.optimization = true; appArchitect['build'].options.buildOptimizer = true; appArchitect['build'].options.aot = true; - appArchitect['build'].options.fileReplacements = [ - { - replace: 'src/environments/environment.ts', - with: 'src/environments/environment.prod.ts', - }, - ]; appArchitect['build'].options.i18nMissingTranslation = 'error'; appArchitect['build'].options.vendorChunk = true; appArchitect['build'].options.sourceMap = true; diff --git a/tests/legacy-cli/e2e/tests/misc/third-party-decorators.ts b/tests/legacy-cli/e2e/tests/misc/third-party-decorators.ts index 75cfd64063af..8aac6af53eb4 100644 --- a/tests/legacy-cli/e2e/tests/misc/third-party-decorators.ts +++ b/tests/legacy-cli/e2e/tests/misc/third-party-decorators.ts @@ -114,7 +114,6 @@ export default async function () { 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'; @@ -126,7 +125,7 @@ export default async function () { imports: [ BrowserModule, StoreModule.forRoot({ count: counterReducer }), - !environment.production ? StoreDevtoolsModule.instrument() : [], + StoreDevtoolsModule.instrument(), EffectsModule.forRoot([AppEffects]) ], providers: [], diff --git a/tests/legacy-cli/e2e/tests/test/test-environment.ts b/tests/legacy-cli/e2e/tests/test/test-environment.ts index 0342a6a5b982..e699a7ceb298 100644 --- a/tests/legacy-cli/e2e/tests/test/test-environment.ts +++ b/tests/legacy-cli/e2e/tests/test/test-environment.ts @@ -1,14 +1,22 @@ import { ng } from '../../utils/process'; -import { writeFile } from '../../utils/fs'; +import { writeFile, writeMultipleFiles } from '../../utils/fs'; import { updateJsonFile } from '../../utils/project'; export default function () { // Tests run in 'dev' environment by default. return ( - writeFile( - 'src/app/environment.spec.ts', - ` - import { environment } from '../environments/environment'; + writeMultipleFiles({ + 'src/environment.prod.ts': ` + export const environment = { + production: true + };`, + 'src/environment.ts': ` + export const environment = { + production: false + }; + `, + 'src/app/environment.spec.ts': ` + import { environment } from '../environment'; describe('Test environment', () => { it('should have production disabled', () => { @@ -16,7 +24,7 @@ export default function () { }); }); `, - ) + }) .then(() => ng('test', '--watch=false')) .then(() => updateJsonFile('angular.json', (configJson) => { @@ -25,8 +33,8 @@ export default function () { production: { fileReplacements: [ { - src: 'src/environments/environment.ts', - replaceWith: 'src/environments/environment.prod.ts', + src: 'src/environment.ts', + replaceWith: 'src/environment.prod.ts', }, ], }, @@ -39,7 +47,7 @@ export default function () { writeFile( 'src/app/environment.spec.ts', ` - import { environment } from '../environments/environment'; + import { environment } from '../environment'; describe('Test environment', () => { it('should have production enabled', () => {