Skip to content

Commit

Permalink
build: consistently set service-worker activation with custom webpack…
Browse files Browse the repository at this point in the history
… build (#569)
  • Loading branch information
dhhyi authored Feb 24, 2021
1 parent 3f5f799 commit afc7bfd
Show file tree
Hide file tree
Showing 10 changed files with 23 additions and 40 deletions.
6 changes: 5 additions & 1 deletion angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,11 @@
"aot": false,
"styles": ["src/styles/themes/default/style.scss"],
"assets": [
{ "glob": "**/*", "input": "src/assets/", "output": "/assets/" }
{
"glob": "**/*",
"input": "src/assets/",
"output": "/assets/"
}
],
"scripts": [],
"fileReplacements": [
Expand Down
3 changes: 1 addition & 2 deletions docs/concepts/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,7 @@ This provides the most flexible way of configuring the application at runtime.

### Build Settings

One example for a build time configuration is the property `serviceWorker`, which is managed in the _environment.ts_ and used to activate the `ServiceWorker` module.
Another example of such a build setting is the property `production` as multiple debug modules are only compiled into the application when running in development mode.
One example for a build time configuration is the property `serviceWorker`, which is managed in the _angular.json_ configurations and used to activate the [service worker](./progressive-web-app.md#service-worker).

In general, properties available at build time can only be supplied by Angular CLI environments (see above).

Expand Down
1 change: 0 additions & 1 deletion e2e/test-schematics.sh
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,6 @@ node scripts/init-local-environment -f

node schematics/customization/service-worker false
grep '"serviceWorker": false' angular.json
grep 'serviceWorker: false' src/environments/environment.local.ts

git add -A
npm run clean
Expand Down
23 changes: 0 additions & 23 deletions schematics/customization/service-worker/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,26 +29,3 @@ Object.keys(build.configurations).forEach(key => {

fs.writeFileSync('./angular.json', stringify(angularJson, null, 2));
execSync('npx prettier --write angular.json');

// replace in environments
const tsMorphProject = new Project();
tsMorphProject.addSourceFilesAtPaths('src/environments/environment*.ts');

tsMorphProject
.getSourceFiles()
.filter(file => !file.getBaseName().endsWith('.model.ts') && file.getBaseName() !== 'environment.ts')
.forEach(file => {
file
.forEachDescendantAsArray()
.filter(stm => stm.getKind() == ts.SyntaxKind.VariableDeclaration && stm.getName() === 'environment')
.map(stm => stm.getInitializer())
.forEach(objectLiteralExpression => {
const property = objectLiteralExpression.getProperty('serviceWorker');
if (property) {
property.setInitializer(`${enable}`);
}
});
});

tsMorphProject.saveSync();
execSync('npx prettier --write src/environments/*.*');
1 change: 0 additions & 1 deletion scripts/init-local-environment.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ const extraFeatures: typeof environment.features =
export const environment: Environment = {
...ENVIRONMENT_DEFAULTS,
serviceWorker: false,
defaultDeviceType: 'desktop',
icmBaseURL: 'https://pwa-ish-demo.test.intershop.com',
Expand Down
4 changes: 1 addition & 3 deletions src/app/core/core.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import { ServiceWorkerModule } from '@angular/service-worker';
import { TranslateModule } from '@ngx-translate/core';
import { BrowserCookiesModule } from 'ngx-utils-cookies-port';

import { environment } from '../../environments/environment';

import { AppearanceModule } from './appearance.module';
import { ConfigurationModule } from './configuration.module';
import { ExtrasModule } from './extras.module';
Expand All @@ -29,7 +27,7 @@ import { DefaultErrorhandler } from './utils/default-error-handler';
HttpClientModule,
IdentityProviderModule,
InternationalizationModule,
ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.serviceWorker }),
ServiceWorkerModule.register('ngsw-worker.js', { enabled: SERVICE_WORKER }),
StateManagementModule,
],
providers: [
Expand Down
4 changes: 0 additions & 4 deletions src/environments/environment.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,6 @@ export interface Environment {
// default device type used for initial page responses
defaultDeviceType: DeviceType;

// enable or disable service worker
serviceWorker: boolean;

// configuration of the available locales - hard coded for now
locales: Locale[];

Expand Down Expand Up @@ -111,7 +108,6 @@ export const ENVIRONMENT_DEFAULTS: Environment = {
features: ['compare', 'recently', 'rating', 'wishlists'],

/* PROGRESSIVE WEB APP CONFIGURATIONS */
serviceWorker: false,
smallBreakpointWidth: 576,
mediumBreakpointWidth: 768,
largeBreakpointWidth: 992,
Expand Down
2 changes: 2 additions & 0 deletions src/typings.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ interface NodeModule {

declare var PRODUCTION_MODE: boolean;

declare var SERVICE_WORKER: boolean;

declare var PWA_VERSION: string;
17 changes: 13 additions & 4 deletions templates/webpack/webpack.custom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@ const log = (...txt) => {
console.log('Custom Webpack:', ...txt);
};

export default (config: webpack.Configuration, _: CustomWebpackBrowserSchema, targetOptions: TargetOptions) => {
export default (
config: webpack.Configuration,
angularJsonConfig: CustomWebpackBrowserSchema,
targetOptions: TargetOptions
) => {
const configurations = targetOptions.configuration.split(',');
const production = configurations.includes('production');
const specificConfigurations = configurations.filter(x => x !== 'production');
if (specificConfigurations.length > 1) {
console.warn('cannot handle multiple configurations, ignoring', specificConfigurations.slice(1));
Expand All @@ -29,16 +32,22 @@ export default (config: webpack.Configuration, _: CustomWebpackBrowserSchema, ta
log('deactivated directTemplateLoading');
}

// set production mode
// set production mode and service-worker
const production = configurations.includes('production');
const serviceWorker = !!angularJsonConfig.serviceWorker;
config.plugins.push(
new webpack.DefinePlugin({
PWA_VERSION: JSON.stringify(
`${require('../../package.json').version} built ${new Date()} - production:${production}`
`${require('../../package.json').version} built ${new Date()} - configuration:${
targetOptions.configuration
} service-worker:${serviceWorker}`
),
PRODUCTION_MODE: production,
SERVICE_WORKER: serviceWorker,
})
);
log('setting production:', production);
log('setting serviceWorker:', serviceWorker);

if (production) {
// splitChunks not available for SSR build
Expand Down
2 changes: 1 addition & 1 deletion tslint.json
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@
{
"import": ".*",
"from": ".*environments/environment.*",
"filePattern": "^.*/app/((?!(module|core/store/core/configuration/configuration\\.reducer|core/utils/state-transfer/state-properties\\.service|injection-keys)\\.ts).)*$",
"filePattern": "^.*/app/((?!(app(.server)?.module|core/store/core/configuration/configuration\\.reducer|core/utils/state-transfer/state-properties\\.service|injection-keys)\\.ts).)*$",
"message": "Importing environment is not allowed. Inject needed properties instead."
},
{
Expand Down

0 comments on commit afc7bfd

Please sign in to comment.