Showing posts with label SPFX. Show all posts
Showing posts with label SPFX. Show all posts

Friday, 27 March 2026

🚀 Fixing SPFx Caching Issues (Especially for Extensions) + How to Fix SPFx Extension Caching Issues using Content Hashing in Heft

🛠️ Modernizing SPFx Extension Deployments: Beyond Query String Versioning

If you develop SPFx Extensions, you’ve likely faced "file resistance"—where the browser or CDN refuses to drop a cached version of your script even after a fresh deployment.

While this happens across both Gulp and Heft-based builds, the way we solve it has evolved.

The Problem: Why "Classic" Versioning Falls Short

In the past, we relied on the "Classic JS" method: appending a version as a query string (e.g., my-extension.js?v=1.1).

While better than nothing, query strings have major flaws:

  • Manual Overhead: You have to remember to bump the version.

  • Inconsistent Caching: Some CDNs and proxy servers are configured to ignore query strings entirely, serving the old file anyway.

  • All-or-Nothing: A version bump often forces a reload of the entire bundle, even if only a tiny part of the code changed.

The Solution: Content Hashing

The modern standard is to bake the versioning directly into the filename using a Content Hash. Instead of my-extension.js, your build produces my-extension_a1b2c3d4.js.

Why this is superior:

  1. Immutability: Since the filename is unique to the content, the browser sees it as a brand-new resource, completely bypassing "file resistance."

  2. Automation: The hash is generated automatically based on your code changes. No change? No new hash.

  3. Atomic Updates: Only the files that actually changed get a new name, preserving the cache for everything else.

🔍 Understanding Where the File Resists & Packs

To understand why this works, it helps to look at how SPFx packages files. When the toolchain packs your solution, it moves through this pipeline:

srclibdist.sppkgTenant App Catalog/SiteAssets

After deployment, your JS bundle lives in:SiteAssets/ClientSideAssets/<GUID>/

Because SharePoint assigns a static GUID directory for the solution assets, having a static filename inside that folder makes it incredibly easy for the SharePoint CDN to cache the file aggressively. By using a content hash, you force SharePoint to see the file as brand new inside that GUID folder.

Implementation for Heft-Based Toolchains

If you are using a Heft-based toolchain, you can implement this fix by adding the following to your spfx-customize-webpack.js (Add spfx-customize-webpack.js file in config folder):

'use strict';

module.exports = function (generatedConfiguration) {

  generatedConfiguration.output = generatedConfiguration.output || {};

  generatedConfiguration.output.filename = '[name]_[contenthash].js';

  return generatedConfiguration;

};



By moving to [contenthash], you ensure that your extensions pack and deploy reliably every time, without the "sticky" cache issues of the past.

💡 Troubleshooting Tip: How to Verify It's Working

To verify that your Heft toolchain is correctly hashing the files, run your build and check the local packing output:

  1. Look in your local temp/deploy or dist folder.

  2. Verify that your output JavaScript files now look like my-webpart_df23a1b4e.js instead of standard, flat names.

  3. If you see the hashes there, they will be bundled correctly into your .sppkg file for deployment!

(Content writing support for this post provided by an AI assistant.)

Monday, 11 November 2024

Setting Up an Angular Application (18) in SharePoint Framework (SPFx)

Introduction:

This guide will walk you through the process of integrating Angular with SharePoint Framework (SPFx), ideal for developers aiming to build dynamic applications within SharePoint. You'll learn how to set up the environment, configure Angular with SPFx, and deploy your application. This setup enables you to leverage Angular's capabilities while working within the SharePoint ecosystem.

Prerequisites:

Ensure that the following software and tools are installed:

  1. SharePoint SPFx Environment:  Set up the SharePoint SPFx environment. Follow the official guide here: Microsoft SPFx Setup.
  2. Node.js : Install Node.js version 18.
  3. Angular CLIInstall Angular CLI globally using: npm install -g @angular/cli

Note: Running `npm install -g @angular/cli` will install the latest version. To specify version 18, use `npm install -g @angular/cli@18`.

  • Code Editor:
    Install any code editor of your choice. Visual Studio Code is recommended for ease of use with SPFx.
Install any code editor of your choice. Visual Studio Code is recommended for ease of use with SPFx.

Steps to Create an SPFx Application with Angular

Step 1: Create an Angular Workspace

1. Open PowerShell (or an alternative command line) and navigate to your desired directory (e.g.): cd "D:\AKS\SPFX\Demo_spfx_ang"

2. Create a new Angular application using the command: ng new ang-app

3. When prompted:

  • Choose a stylesheet format: Select `css` (or your preferred option).
  • - Enable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering)?: Select `N`.

*SSR renders a fully front-end application on the server instead of the browser, while SSG creates a set of static HTML files for the app. Selecting 'No' simplifies the setup for basic applications.*

4. The command will install the required packages and set up your Angular solution. Ignore any Git configuration errors.

5. Once installation is complete, open your project in Visual Studio Code: code .

Step 2: Add Angular Elements

1. Open the terminal in Visual Studio Code and navigate to your Angular project: cd ang-app

2. Install the Angular Elements package: npm install @angular/elements@latest

3. Test the Angular Application :ng serve

If the application loads successfully in the browser, your setup is correct.


*Note: Angular will generate additional files (e.g., `polyfill.js`, `main.js`, `styles.js`) during build, which are required for SPFx.*


Step 3: Create the SPFx Application

1. Navigate back to your root directory in PowerShell and create a new folder for the SPFx application: cd "D:\AKS\SPFX\Demo_spfx_ang\spfx_app"

2. Create a new SPFx web part using the Yeoman generator: yo @microsoft/sharepoint

3. When prompted by Yeoman, configure as follows:

  • Component Type: WebPart
  • Web Part Name: Choose a descriptive name for your web part.
  • Template: Select 'No framework.'

4. Once Yeoman creates the project structure and installs dependencies, lock the packages to prevent version conflicts: npm shrinkwrap

5. Open the root folder in Visual Studio Code: code .

Step 4: Configure Angular to Work with SPFx

Modify angular.json

  1. Create an appfiles folder in the SPFx web part project (spfxAppWebPart).

  2. In angular.json (in the Angular project), update the outputPath to:

    "outputPath": "../spfx-app/src/webparts/spfxAppWebpart/appfiles"

    This change will ensure required files (polyfill.js, main.js, styles.js) are compiled into the appfiles folder.

  3. Change outputHashing to "none":

    "outputHashing": "none"

    This prevents adding unique hashes to filenames, so you won’t need to update file references in SPFx every time you rebuild the Angular project.

  4. Increase the budgets for maximumWarning and maximumError if necessary (optional):

    "maximumWarning": "5mb",
    "maximumError": "20mb"

    This adjustment helps avoid errors if the project exceeds default file size limits.

    So Overall changes in the angular.json will be as follows:


     

Modify main.ts

Update main.ts to define Angular components as custom elements:

import { ApplicationRef } from '@angular/core';
import { createApplication } from '@angular/platform-browser'; import { createCustomElement } from '@angular/elements'; import { appConfig } from './app/app.config'; import { AppComponent } from './app/app.component'; (async () => { const app: ApplicationRef = await createApplication(appConfig); const appComponent = createCustomElement(AppComponent, { injector: app.injector }); customElements.define('app-root', appComponent); })();


Note: Replace AppComponent with your default component if it differs.

Step 5: Integrate Angular with SPFx Web Part

  1. Import Angular Files in SPFx

    In the Webpart.ts file, add the following lines to import Angular styles and scripts:

    require('./appfiles/browser/styles.css');
    require('./appfiles/browser/polyfills.js'); require('./appfiles/browser/main.js');

    Order matters: Ensure these files are imported in this exact sequence.


  2. Render the Angular Component

    In the render() method of Webpart.ts, add:

    this.domElement.innerHTML = `<app-root></app-root>`;



Step 6: Testing the SPFx Application

  1. Trust the Developer Certificate
    Change to the SPFx app directory and run: gulp trust-dev-cert

    This step adds SPFx’s certificate to the trusted authorities on your machine.

  2. Change the {tenantDomain} with your SharePoint online site url. 


  3. Serve the Applicationgulp serve

    This will compile the solution and launch the SharePoint Workbench. Add the new web part to the Workbench to verify functionality.


Conclusion

Following these steps, you’ll have successfully set up an Angular application within the SharePoint Framework. This setup provides the flexibility to use Angular features in SPFx and offers a straightforward path for developing complex SharePoint solutions.

Cheers and happy coding!😊