Both web parts get bundled in one single JavaScript file. This situation has the below points to consider.
- When a single web part is added to a page, actually both are loaded.
- If both the web parts are on one page, this will reduce the load time.
It is better to split both the web parts in separate files to reduce what is loaded on the page.
- {
- "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
- "version": "2.0",
- "bundles": {
- "my-spfx-1": {
- "components": [
- {
- "entrypoint": "./lib/webparts/webpart1/webpart1.js",
- "manifest": "./src/webparts/webpart1/webpart1.manifest.json"
- }
- ]
- },
- "my-spfx-2": {
- "components": [
- {
- "entrypoint": "./lib/webparts/webpart2/webpart2.js",
- "manifest": "./src/webparts/webpart2/webpart2.manifest.json"
- }
- ]
- }
- },
- "externals": {},
- "localizedResources": {}
- }
Loading third party libraries dynamically
SharePoint Framework uses a webpack to bundle the solution. Webpack allows the dynamic import of part of an application. Consider an example of
Moment library used in our SPFx web part to manage date operations.
Normal import
In the below example, Moment library will be included in the final package, irrespective of whether GetLongTime is called or not.
-
- import * as moment from moment
- .
- .
- export default class DateTimeClass {
- public GetLongTime(dateTime:string){
- return moment(dateTime).format("LLLL");
- }
- }
Dynamic import
In the below example, Moment library is loaded asynchronously only when the GetLongTime function is called.
- export default class DateTimeClass {
- public async GetLongTime(dateTime:string){
- const moment = await import(
-
- 'moment'
- );
- return moment(dateTime).format("LLLL");
- }
- }
Reference external libraries externally
We often use external libraries (e.g. jQuery) in our SPFx web part. Adding these external libraries as npm packages, and including them inside the final package, making it bulky. The external libraries can be referenced externally as below,
- Under the config folder, open the config.json file.
- To load jQuery from CDN location, add an entry to the externals section.
- {
- "entries": [
- {
- "entry": "./lib/webparts/helloWorld/HelloWorldWebPart.js",
- "manifest": "./src/webparts/helloWorld/HelloWorldWebPart.manifest.json",
- "outputPath": "./dist/helloworld.bundle.js"
- }
- ],
- "externals": {
- "@microsoft/sp-client-base": "node_modules/@microsoft/sp-client-base/dist/sp-client-base.js",
- "@microsoft/sp-client-preview": "node_modules/@microsoft/sp-client-preview/dist/sp-client-preview.js",
- "@microsoft/sp-lodash-subset": "node_modules/@microsoft/sp-lodash-subset/dist/sp-lodash-subset.js",
- "jquery": "https://code.jquery.com/jquery-3.1.0.min.js"
- },
- "localizedResources": {
- "helloWorldStrings": "webparts/helloWorld/loc/{locale}.js"
- }
- }
Import jQuery in SPFx web part as below,
- import * as $ from 'jquery';
Analyzing your bundle
Extend the Webpack configuration in your SPFx project to understand the bundle.
Run the below command to install the webpack-bundle-analyzer package to your SPFx solution
- npm install webpack-bundle-analyzer --save-dev
Update the contents of the gulpfile.js file as below,
- 'use strict';
-
- const gulp = require('gulp');
- const path = require('path');
- const build = require('@microsoft/sp-build-web');
- const bundleAnalyzer = require('webpack-bundle-analyzer');
-
- build.configureWebpack.mergeConfig({
- additionalConfiguration: (generatedConfiguration) => {
- const lastDirName = path.basename(__dirname);
- const dropPath = path.join(__dirname, 'temp', 'stats');
- generatedConfiguration.plugins.push(new bundleAnalyzer.BundleAnalyzerPlugin({
- openAnalyzer: false,
- analyzerMode: 'static',
- reportFilename: path.join(dropPath, `${lastDirName}.stats.html`),
- generateStatsFile: true,
- statsFilename: path.join(dropPath, `${lastDirName}.stats.json`),
- logLevel: 'error'
- }));
-
- return generatedConfiguration;
- }
- });
-
- build.initialize(gulp);
The "gulp bundle" command will generate a visualization file at ./temp/stats/[solution-name].stats.html file.
Summary
In this article, we explored the commonly observed behaviors and optimization techniques to build better solutions in SPFx. The performance of the SPFx web part can be optimized by following simple techniques. This will help to keep the bundle size within limits and improve the overall performance.
Gaurav GoyalPosted Apr 30, 2020, 6:33 AM
Is it not possible in SPFx webpart component?
Gaurav GoyalPosted Apr 30, 2020, 5:00 AM
Hi Nanddeep, If I include all files in SPFx bundle, it increases the size of the bundle. But some code are common & shared in web parts. I want to create separate files for shared code & common code in spfx. How can I do that?