Saturday, August 12, 2017

Dealing with package errors when building SharePoint Framework solutions

I’ve been working on a web part for a customer lately and was going to bundle it up and install it at the customers tenant. When I ran gulp --ship to prepare the bundle I got the following error:

[14:47:51] Error - [webpack] 'dist':
cylinder-configurator.bundle.js from UglifyJs
Unexpected token: name (finish) [cylinder-configurator.bundle.js:5976,6]

Something broke when the build process was running uglify-js. I opened by bundle in the temp\deploy folder and looked at line 5676. This was a reference to MathLab which was included my the npm package pica which I’m using in this project.

I figured as much as to solve my issue I needed to break pica out of the main build process, but how?

image

Again, my good friend Waldek pointed me in the right direction and he has actually written about this before, and the needed documentation can be found in the official SPFx documentation Add an external library to your SharePoint client-side web part.

In order to not have the build process include the library inside the bundle, you need to externalize it. But I didn’t want to put it on a CDN. By adding a reference to the externals section in config.json pointing to the .js file from the node_modules folder, the resulting bundle will keep the library as a separate file.

"externals": {
    "pica": "node_modules/pica/dist/pica.min.js"
}

Running gulp --ship with this in place the error is gone and I get two files in temp/deploy instead of one, one for pica and one for the web part.

image

You can see the main bundle is quite large, as I haven’t externalized Office UI Fabric yet in this part.

Summary

Adding external libraries to a SharePoint Framework solution is quite easy, but depending on the library you might run into packaging issues and you need to know how to work around them. Making sure you know the different ways to externalize a library and how to optimize the resulting bundle all helps you reach the final goal that much quicker.