npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@sitelintcode/angular-static-assets-hash

v0.0.23

Published

Create a list of static assets and a hash for each file.

Downloads

287

Readme

Angular and create a list of static assets with their hashes

Cache busting static files (images, pdfs, pngs, etc.) for the Angular application.

When building, Angular will add a hash to JavaScript, CSS, and assets referenced in your CSS files. However, what about images and other assets you have in your assets folder that you reference in templates?

Those assets are not hashed.

The package looks for static assets, creates a list of them with their hashes, and saves it as a JSON file. This is useful when you want to change the same static asset without changing the name and ensure that the browser will always fetch the latest version.

Note that the hash is created the same way as for Subresource Integrity (SRI).

Getting started

Install

npm install @sitelintcode/angular-static-assets-hash --save--dev

CLI

You can use directly in package.json script or through npx createAngularStaticHashes [params].

Parameters

  • --staticAssetsPath=[path to static assets]. Default: [angular root folder]/assets/images
  • --globPattern=[glob pattern]. Default: /**/*

Import

import { createHashes } from '@sitelintcode/angular-static-assets-hash';

const angularStaticAssetsHash = new AngularStaticAssetsHash();

angularStaticAssetsHash.createHashes();

Example output

{
  "assets/images/example.png": "iY5RY0G8wePLPRkZSTgW2XYZFZ7kQOqXoJTFpQFG5nI",
  "assets/images/avatar.svg": "7A7qFs_iOghsdUtLG-7y-5cxT3FC8S_BRXl5ldsNY7Y",
  "assets/images/body-background.svg": "K2FTBtDsxgKLQFr4BUW1ptnLWqPCKPyGypHCBTfcctQ",
  "assets/images/icons.svg": "Ka-ngr7Fht6ucmN03kzJeMN7f2iOtnkD-D63QJ01jhM"
}

Angular

Once the list of static assets is created, we need to have a way to use it with Angular. For that purpose, we can use an Angular Pipe.

Notes

  1. Notice the staticAssetsList private property. It points to the location of assets.json file is created.
  2. The default path for static assets is [angular root path]/assets/images.

TypeScript Pipe for Angular

import { Pipe, PipeTransform } from '@angular/core';

import staticAssetsList from '../../assets.json';

@Pipe({
  name: 'fileHash'
})
export class FileHashPipe implements PipeTransform {

  private staticAssets: { [key: string]: string };

  constructor() {
    this.staticAssets = staticAssetsList;
  }

  private addParamsToUrl(givenUrl: string, urlParameters: string): string {

    if (typeof urlParameters !== 'string' || urlParameters.length === 0) {
      return givenUrl;
    }

    const urlSplitByHash: string[] = givenUrl.split('#');
    const hash: string = urlSplitByHash[1] || '';
    const params: string[] = urlParameters.split('&');
    let url: string = urlSplitByHash[0];

    if (url.indexOf('?') === -1) {
      url += '?';
    } else {
      url += '&';
    }

    url += params.map((paramItem: string): string => {
      const p: string[] = paramItem.split('=');

      return `${p[0]}=${window.encodeURIComponent(p[1])}`;
    })
      .join('&');

    url = url.slice(0, -1); // remove last &

    return hash ? `${url}#${hash}` : url;
  }

  private getHashForStaticAsset(assetPath: string): string {
    const path: string = assetPath.split('#')[0];

    if (typeof ResourceUtility.staticAssets[path] === 'string') {
      return this.addParamsToUrl(assetPath, `c=${this.staticAssets[path]}`);
    }

    return '';
  }

  public transform(filePath: string): string {
    const filePathWithCacheHash: string = this.getHashForStaticAsset(filePath);

    return filePathWithCacheHash;
  }
}

Later in the code the pipe can be used in the following way.

Image example

<img attr.src="{{ 'assets/images/example.png' | fileHash }}" alt="">

The hash is quite useful when we want to manage, e.g., one file with all <svg> icons. While you could change your single file with all svg icons all the time, your code remains the same.

SVG sprite example

<svg aria-hidden="true" focusable="false" viewBox="0 0 48 48" width="32" height="32">
  <use attr.href="{{ 'assets/images/icons.svg#image-logo' | fileHash }}"></use>
</svg>

Workable example

You can see the implementation by looking at the source code of the app based on Angular. The app refers to SiteLint Audit Platform.

Contributing

Contributions are welcome, and greatly appreciated! Contributing doesn't just mean submitting pull requests. There are many different ways for you to get involved, including answering questions on the issues, reporting or triaging bugs, and participating in the features evolution process.

License

MOZILLA PUBLIC LICENSE, VERSION 2.0