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 .hbs
as 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.
let hbsCopy = build.subTask('hbsCopy', (gulp, buildOptions, done) => {
// make sure preBuild file will be copied again
gulp.src('./src/**/*.hbs')
.pipe(gulp.dest('./lib/'));
// Don't forget to tell SPFx you are done
done();
})
// register task to prebuild process
build.rig.addPreBuildTask(hbsCopy);
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.
‘copy-static-assets.json’ approach
Another more SPFx like approach is to add a configuration file named copy-static-assets.json
in the config folder.
Inside the ‘includeExtensions’ section defines what files get copied to the lib
folder.
In case of Handlebars the JSON file containing the following information:
{
"includeExtensions": [
"hbs"
]
}
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-assets
task shows up.
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.json
approach 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.