How to use @angular/service-worker - 10 common examples

To help you get started, we’ve selected a few @angular/service-worker examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github HelixOne / leto / webpack.config.aot.js View on Github external
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;
const ClosureCompiler = require('google-closure-compiler-js').webpack;
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const ngtools = require('@ngtools/webpack');
const CompressionPlugin = require("compression-webpack-plugin");
const ServiceWorkerWebpackPlugin = require('serviceworker-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin')
const buildTime = Date.now()
const ClosureCompilerPlugin = require('webpack-closure-compiler');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const AngularServiceWorkerPlugin = require('@angular/service-worker/webpack').default;
console.log(AngularServiceWorkerPlugin)
const config = {
    context: path.join(__dirname + '/src'),
    entry: {
        'polyfills': './polyfills.ts',
        'vendor': './vendor.ts',
        'main': './main.ts'
    },

    // enable loading modules relatively
    resolve: {
        extensions: ['.ts', '.js'],
        //   modules: [__dirname + "/src", "node_modules"]
    },

    module: {
github HelixOne / leto / webpack.config.js View on Github external
const webpack = require('webpack');
const path = require('path');
const webpackMerge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const LiveReloadPlugin = require('webpack-livereload-plugin');
const fs = require('fs')
var privateKey = fs.readFileSync('host.key', 'utf8');
var certificate = fs.readFileSync('host.crt', 'utf8');
var credentials = { key: privateKey, cert: certificate };
//const ServiceWorkerWebpackPlugin = require('serviceworker-webpack-plugin');
const AngularServiceWorkerPlugin = require('@angular/service-worker/webpack').default;
console.log(AngularServiceWorkerPlugin)

// Webpack Config
var webpackConfig = {
  context: path.join(__dirname + '/src'),

  entry: {
    'polyfills': './polyfills.ts',
    'vendor': './vendor.ts',
    'main': './main.ts',
  },

  output: {
    publicPath: '',
    path: path.resolve(__dirname, './dist/www'),
  },
github alexjlockwood / ShapeShifter / src / app / modules / editor / editor.module.ts View on Github external
PropertyInputComponent,
    RootComponent,
    ScrollGroupDirective,
    SplashScreenComponent,
    SplitterComponent,
    TimelineAnimationRowComponent,
    ToolbarComponent,
    ToolPanelComponent,
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FlexLayoutModule,
    FormsModule,
    HttpClientModule,
    ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production }),
    StoreModule.forRoot(reducers, { metaReducers }),
    // Angular material components.
    MatButtonModule,
    MatDialogModule,
    MatIconModule,
    MatInputModule,
    MatMenuModule,
    MatOptionModule,
    MatRadioModule,
    MatSlideToggleModule,
    MatSnackBarModule,
    MatToolbarModule,
    MatTooltipModule,
  ],
  providers: [{ provide: ErrorHandler, useFactory: errorHandlerFactory }],
  entryComponents: [ConfirmDialogComponent, DemoDialogComponent, DropFilesDialogComponent],
github angular / angular-cli / lib / broccoli / angular2-app.js View on Github external
mangle: false
      });

      // Required here since the package isn't installed for non-mobile apps.
      var ServiceWorkerPlugin = require('@angular/service-worker').ServiceWorkerPlugin;
      // worker.js is needed so it can be copied to dist
      var workerJsTree = new BroccoliFunnel(jsTree, {
        include: ['vendor/@angular/service-worker/dist/worker.js']
      });
      /**
       * ServiceWorkerPlugin will automatically pre-fetch and cache every file
       * in the tree it receives, so it should only receive the app bundle,
       * and non-JS static files from the app. The plugin also needs to have
       * the worker.js file available so it can copy it to dist.
       **/
      var swTree = new ServiceWorkerPlugin(BroccoliMergeTrees([
        bundleTree,
        assetsTree,
        workerJsTree
      ]));
      bundleTree = BroccoliMergeTrees([bundleTree, swTree], {
        overwrite: true
      });
    }

    return BroccoliMergeTrees([nonJsTree, scriptTree, bundleTree], { overwrite: true });
  }
}
github fossasia / susper.com / node_modules / @angular / cli / models / webpack-configs / production.js View on Github external
// So for now we keep it here, but if AngularServiceWorkerPlugin changes we remove it.
            extraPlugins.push(new glob_copy_webpack_plugin_1.GlobCopyWebpackPlugin({
                patterns: [
                    'ngsw-manifest.json',
                    { glob: 'ngsw-manifest.json',
                        input: path.resolve(projectRoot, appConfig.root), output: '' }
                ],
                globOptions: {
                    cwd: projectRoot,
                    optional: true,
                },
            }));
            // Load the Webpack plugin for manifest generation and install it.
            const AngularServiceWorkerPlugin = require('@angular/service-worker/build/webpack')
                .AngularServiceWorkerPlugin;
            extraPlugins.push(new AngularServiceWorkerPlugin({
                baseHref: buildOptions.baseHref || '/',
            }));
            // Copy the worker script into assets.
            const workerContents = fs.readFileSync(workerPath).toString();
            extraPlugins.push(new static_asset_1.StaticAssetPlugin('worker-basic.min.js', workerContents));
            // Add a script to index.html that registers the service worker.
            // TODO(alxhub): inline this script somehow.
            entryPoints['sw-register'] = [registerPath];
        }
    }
    extraPlugins.push(new bundle_budget_1.BundleBudgetPlugin({
        budgets: appConfig.budgets
    }));
    if (buildOptions.extractLicenses) {
        extraPlugins.push(new license_webpack_plugin_1.LicenseWebpackPlugin({
            pattern: /^(MIT|ISC|BSD.*)$/,
github angular / angular-cli / packages / angular_devkit / build_webpack / src / angular-cli-files / models / webpack-configs / production.ts View on Github external
extraPlugins.push(new GlobCopyWebpackPlugin({
        patterns: [
          'ngsw-manifest.json',
          { glob: 'ngsw-manifest.json',
            input: path.resolve(projectRoot, appConfig.root), output: '' }
        ],
        globOptions: {
          cwd: projectRoot,
          optional: true,
        },
      }));

      // Load the Webpack plugin for manifest generation and install it.
      const AngularServiceWorkerPlugin = require('@angular/service-worker/build/webpack')
        .AngularServiceWorkerPlugin;
      extraPlugins.push(new AngularServiceWorkerPlugin({
        baseHref: buildOptions.baseHref || '/',
      }));

      // Copy the worker script into assets.
      const workerContents = fs.readFileSync(workerPath).toString();
      extraPlugins.push(new StaticAssetPlugin('worker-basic.min.js', workerContents));

      // Add a script to index.html that registers the service worker.
      // TODO(alxhub): inline this script somehow.
      entryPoints['sw-register'] = [registerPath];
    }
  }

  extraPlugins.push(new BundleBudgetPlugin({
    budgets: appConfig.budgets
  }));
github angular / angular-cli / packages / @angular / cli / utilities / service-worker / index.ts View on Github external
export function augmentAppWithServiceWorker(projectRoot: string, appRoot: string,
    outputPath: string, baseHref: string): Promise {
  // Path to the worker script itself.
  const workerPath = resolveProjectModule(projectRoot, '@angular/service-worker/ngsw-worker.js');
  const safetyPath = path.join(path.dirname(workerPath), 'safety-worker.js');
  const configPath = path.resolve(appRoot, 'ngsw-config.json');

  if (!fs.existsSync(configPath)) {
    throw new Error(oneLine`Error: Expected to find an ngsw-config.json configuration
      file in the ${appRoot} folder. Either provide one or disable Service Worker
      in .angular-cli.json.`);
  }
  const config = fs.readFileSync(configPath, 'utf8');

  const Generator = require('@angular/service-worker/config').Generator;
  const gen = new Generator(new CliFilesystem(outputPath), baseHref);
  return gen
    .process(JSON.parse(config))
    .then((output: Object) => {
      const manifest = JSON.stringify(output, null, 2);
      fs.writeFileSync(path.resolve(outputPath, 'ngsw.json'), manifest);
      // Copy worker script to dist directory.
      const workerCode = fs.readFileSync(workerPath);
      fs.writeFileSync(path.resolve(outputPath, 'ngsw-worker.js'), workerCode);

      // If @angular/service-worker has the safety script, copy it into two locations.
      if (fs.existsSync(safetyPath)) {
        const safetyCode = fs.readFileSync(safetyPath);
        fs.writeFileSync(path.resolve(outputPath, 'worker-basic.min.js'), safetyCode);
        fs.writeFileSync(path.resolve(outputPath, 'safety-worker.js'), safetyCode);
      }
    });
github fossasia / susper.com / node_modules / @angular / cli / utilities / service-worker / index.js View on Github external
function augmentAppWithServiceWorker(projectRoot, appRoot, outputPath, baseHref) {
    // Path to the worker script itself.
    const workerPath = require_project_module_1.resolveProjectModule(projectRoot, '@angular/service-worker/ngsw-worker.js');
    const safetyPath = path.join(path.dirname(workerPath), 'safety-worker.js');
    const configPath = path.resolve(appRoot, 'ngsw-config.json');
    if (!fs.existsSync(configPath)) {
        throw new Error(common_tags_1.oneLine `Error: Expected to find an ngsw-config.json configuration
      file in the ${appRoot} folder. Either provide one or disable Service Worker
      in .angular-cli.json.`);
    }
    const config = fs.readFileSync(configPath, 'utf8');
    const Generator = require('@angular/service-worker/config').Generator;
    const gen = new Generator(new CliFilesystem(outputPath), baseHref);
    return gen
        .process(JSON.parse(config))
        .then((output) => {
        const manifest = JSON.stringify(output, null, 2);
        fs.writeFileSync(path.resolve(outputPath, 'ngsw.json'), manifest);
        // Copy worker script to dist directory.
        const workerCode = fs.readFileSync(workerPath);
        fs.writeFileSync(path.resolve(outputPath, 'ngsw-worker.js'), workerCode);
        // If @angular/service-worker has the safety script, copy it into two locations.
        if (fs.existsSync(safetyPath)) {
            const safetyCode = fs.readFileSync(safetyPath);
            fs.writeFileSync(path.resolve(outputPath, 'worker-basic.min.js'), safetyCode);
            fs.writeFileSync(path.resolve(outputPath, 'safety-worker.js'), safetyCode);
        }
    });
}
github yduartep / angular-full-sample / src / app / app.component.spec.ts View on Github external
beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        BrowserModule,
        CoreModule,
        SharedModule,
        TranslateModule.forRoot(),
        RouterModule.forRoot([]),
        StoreModule,
        EffectsModule,
        ServiceWorkerModule.register('./ngsw-worker.js', {enabled: false})
      ],
      declarations: [
        AppComponent
      ],
      providers: [
        {provide: APP_BASE_HREF, useValue: '/'},
        {provide: 'api.config', useValue: MocksUtil.createMockedApiConfig()},
        {provide: 'defaultLanguage', useValue: 'en'},
        MessageService,
        SwUpdate
      ]
    }).compileComponents();
  }));
  it('should create the app', async(() => {
github rdrahul / AngularPushNotification / src / app / app.component.ts View on Github external
constructor( private SwPush : SwPush , private pushNotification : PushNotificationService ){


    //check if the browser supports service workers
    if( SwPush.isEnabled){

      SwPush.requestSubscription({
        serverPublicKey :  VAPID_PUBLIC
      })
      .then( subscription => {
        
        //send subsription to server
        this.pushNotification.SendSubsriptionToService(subscription).subscribe() ;

      })
      .catch(console.error);
    
    }
  }
}