Solved: how to insert a step into webpack compilation


#1

I am using scripts generated by most recent ‘au new’ (selecting webpack & esnext) w/HMR and I wanted to copy some files each time the webpack compiles the source NOTE: I pass a --client flag into the build/run commands (see an earlier note: Solved-Enough.)

My project has to build for 3 different clients, so I have a ‘banners’ folder as a sibling to the source folder wherein I put all the files that are different per client, most of that works directly but the scss files are a PITA because you cannot dynamically import. So I put an scss folder directly inside the banners folder as a sibling to the client-specific folders and import those files from the source. (I’ve tried symlinks in the past, and git throws a fit.) And then after every edit to those files I copy them to the appropriate client-specific subfolder – human error creeping in… So how to automate the copy everytime webpack builds on a change?

A webpack plugin is the right tool for the job: https://github.com/webpack/docs/wiki/plugins

This block at the top of my webpack.config.js

const Rsync = require('rsync');

class CopyClientFiles {
  constructor(options) { this.client = options.client; }
  // this code copies the modified files from banners/scss to banner/<client>/scss after each run
  apply(compiler) {
    let self = this;
    compiler.plugin('done', function (compilation) {
      const rsync = new Rsync()
        .recursive()
        .source('./banners/scss/')
        .destination(`./banners/${self.client}/scss`);
      rsync.execute(function (error, code, cmd) {
        console.log('Changed Client Files Saved for', self.client);
      });
    });
  }
}

Called at the end

      ...when(!production, new CopyClientFiles({ client })),

Bringing in the right client’s files at the start of the build is done in build.js

import Rsync from 'rsync';
// copy the client files up into the working folder, every compile will copy them back
const rsync = new Rsync()
  .recursive()
  .source(`./banners/${client}/scss/`)
  .destination('./banners/scss');
rsync.execute(function (error, code, cmd) {
  console.log('Source Client Files Imported for', client);
});