Article
0 comment

How to copy files from src to lib folder in SPFx?

Sometimes there is the requirement to move files from your source code directory to the lib folder. These files can be images, JSON files or any imaginable asset that is not recognised by the build chain of SPFx.

There are two ways to achieve this one. One used gulp the other gets accomplished through the configuration of a copy-static-assets.json. Let me explain these to methods what scenarios suites best in which case.

The gulp approach

The gulp approach requires you to make some adjustments in the gulpfile.js. Let me explain this with the example of the handlebars configuration I use in the @pnp/spfx extension generator.

All handlebar files have .hbsas an extension. I can author and edit my handlebar file in the source directory, but at some point, I need to have it in the lib directory to make sure the web part finds the file to load it properly.

One approach is to create a gulp task for that.

The first part of this code snippet defines a new custom gulp task for SPFx that later gets registered to the build process. The copy to the library folder happens after a TypeScript file gets saved.

Custom gulp task shows up in the build chain and copy the files

‘copy-static-assets.json’ approach

Another more SPFx like approach is to add a configuration file named copy-static-assets.jsonin the config folder.

copy-static-assets file in the Visual Studio project

Inside the ‘includeExtensions’ section defines what files get copied to the libfolder.

In case of Handlebars the JSON file containing the following information:

This approach does not need a gulp task. Well, it still needs a gulp task, but this already exists in SPFx. During the build process, it looks for that specific configuration file and moves matching files automatically to the lib directory. To force this copy again any TypeScript files and the copy-static-assetstask shows up.

SPFx integrated way to copy static file

Verdict

Last Friday I ran a short pole on Twitter how many people are aware of the copy-static-assets.json, and only 29% was aware that this option is available.

Which approach is better? The gulp task approach adds a custom gulp task to the configuration and is a valid approach. The config-static-assets.jsonapproach uses an already existing gulp task. So my personal favourite is approach two even if I always have to remind me about that already existing.