Skip to content

Commit

Permalink
feat(@schematics/angular): remove environment files in new applications
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
alan-agius4 committed Sep 27, 2022
1 parent 56a1e8f commit 283b564
Show file tree
Hide file tree
Showing 30 changed files with 68 additions and 401 deletions.
Expand Up @@ -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({
Expand Down Expand Up @@ -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)
Expand Down
Expand Up @@ -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);
Expand Down
Expand Up @@ -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[] = [];
Expand All @@ -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();
});
Expand Down
Expand Up @@ -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',
]);

Expand Down
Expand Up @@ -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' });
Expand Down
Expand Up @@ -43,12 +43,6 @@
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
Expand Down

This file was deleted.

This file was deleted.

Expand Up @@ -7,12 +7,5 @@
*/

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';
Expand Up @@ -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)
Expand Down

This file was deleted.

This file was deleted.

Expand Up @@ -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)
Expand Down

This file was deleted.

This file was deleted.

@@ -1,12 +1,8 @@
import { enableProdMode<% if(!!viewEncapsulation) { %>, ViewEncapsulation<% }%> } from '@angular/core';
<% if(!!viewEncapsulation) { %>import { 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 %>
Expand All @@ -15,4 +11,4 @@ platformBrowserDynamic().bootstrapModule(AppModule, {
<% } else { %>
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
<% } %>
<% } %>
6 changes: 0 additions & 6 deletions packages/schematics/angular/application/index.ts
Expand Up @@ -168,12 +168,6 @@ function addAppToWorkspaceFile(
configurations: {
production: {
budgets,
fileReplacements: [
{
replace: `${sourceRoot}/environments/environment.ts`,
with: `${sourceRoot}/environments/environment.prod.ts`,
},
],
outputHashing: 'all',
},
development: {
Expand Down
12 changes: 1 addition & 11 deletions packages/schematics/angular/application/index_spec.ts
Expand Up @@ -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',
Expand Down Expand Up @@ -147,7 +145,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 () => {
Expand Down Expand Up @@ -261,8 +259,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',
Expand All @@ -289,8 +285,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',
Expand Down Expand Up @@ -318,8 +312,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',
Expand Down Expand Up @@ -399,8 +391,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',
Expand Down
57 changes: 16 additions & 41 deletions packages/schematics/angular/service-worker/index.ts
Expand Up @@ -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';
Expand Down Expand Up @@ -61,50 +56,19 @@ 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);
if (change) {
const recorder = host.beginUpdate(modulePath);
applyToUpdateRecorder(recorder, [change]);
host.commitUpdate(recorder);
}
}

// 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);
if (change) {
const recorder = host.beginUpdate(modulePath);
applyToUpdateRecorder(recorder, [change]);
host.commitUpdate(recorder);
}
}
addImport(host, modulePath, 'ServiceWorkerModule', '@angular/service-worker');
addImport(host, modulePath, 'isDevMode', '@angular/core');

// 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,
Expand Down Expand Up @@ -172,3 +136,14 @@ export default function (options: ServiceWorkerOptions): Rule {
]);
};
}

function addImport(host: Tree, filePath: string, symbolName: string, moduleName: string): void {
const moduleSource = getTsSourceFile(host, filePath);
const change = insertImport(moduleSource, filePath, symbolName, moduleName);

if (change) {
const recorder = host.beginUpdate(filePath);
applyToUpdateRecorder(recorder, [change]);
host.commitUpdate(recorder);
}
}

0 comments on commit 283b564

Please sign in to comment.