Kategorien
Technology

Move React files into custom directories

This morning I tried to rebuild my instapaper clone for Nextcloud from PHP and plain javascript to React, but I needed to move the compiled javascript and CSS files into a custom directory structure for the nextcloud app release. I’m using create-react-app and react-app-rewired and apparently there is no simple way to modify the output directory „build“ to something different.

To avoid additional tools and steps in my process, I decided to write a piece of javascript and execute it with node after building my app via npm. To do this I created the following file move.js next to package.json:

const path = require('path');
const fs = require('fs');

const build = path.resolve(__dirname, 'build');
const target = path.resolve(__dirname, '..');

const errorLogger = (err) => err && console.log(err);

[path.join(target, 'js'), path.join(target, 'css')].forEach(dir =>
  fs.readdir(dir, (err, files) => {
    if (err) throw err;
    files.forEach(file => fs.unlink(path.join(dir, file), errorLogger));
  })
);

// copy javascript+css into custom directories
fs.readdir(build, (err, files) => {
  if (err) throw err;
  // copy javascript+map files
  files.filter(file => {
    return file.endsWith('.js') || file.endsWith('.map');
  }).forEach(file =>
    fs.copyFile(path.join(build, file), path.join(target, 'js', file), errorLogger)
  );
  // copy CSS files
  files.filter(file => {
    return file.endsWith('.css');
  }).forEach(file =>
    fs.copyFile(build + '/' + file, target + '/css/' + file, errorLogger)
  );
});

Now I can modify my npm scripts in package.json:

"scripts": {
  ...,
  "build": "react-app-rewired build && node move.js"
},

When running npm build the files are now copied into the proper directories for JS and CSS in my nextcloud app structure.