Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node: move files in create-react-app template to root post-install

Tags:

npm

reactjs

I have a version of this question with a twist:

I'm building out a create-react-app template that uses both electron and redux.

I want to move config files for webpack and babel from a /src/config directory to root on post install. However, adding "postinstall": "cp /src/config ." to my package.json file isn't working. Looks like that file and not template.json is the right place to add the postinstall script, but for some reason, possibly due to how the templating system manages internal file structures (?) this script is running after install but failing. I have the config files at /template/src/config in my published package.

EDIT: Looks like it runs if I change the postinstall script to "cp template/src/config/* ." but it doesn't copy any files over.

like image 729
lispquestions Avatar asked Sep 12 '25 19:09

lispquestions


2 Answers

File copying after build can be achieved reliably on all operating systems by using the ncp package and an associated script.

How to copy the files after react build?

1. Add ncp as a dependency in 'package.json'

  "dependencies": {
    "ncp": "2.0.0",
    ....
  }

2. Create a file-copy script that will recursively copy files from source to destination

// File name: file-copy.js

var path = require('path');
var ncp = require('ncp').ncp;

ncp.limit = 16;

var srcPath = 'src/config'
var destPath = 'dst/config'

console.log('Copying files...');
ncp(srcPath, destPath, function (err) {
  if (err) {
    return console.error(err);
  }
  console.log('Copying files complete.');
});

3. Add 'node file-copy.js' as an additional step to the build process in package.json

  "scripts": {
    ...  

    "build": "react-scripts build && node file-copy.js"

    ...
  },

Note: After updating the package.json, run the npm install once to install / enable ncp package.

Alternative: npm add ncp on latest version of nodejs will update package.json and also enable ncp in single step.

4. Test the build process by running 'npm run build'

$ npm run build

> [email protected] build /Users/macuser1/stack-overflow/ui
> react-scripts build && node file-copy.js

Creating an optimized production build...
Compiled successfully.

File sizes after gzip:

  40.32 KB         build/static/js/2.db436670.chunk.js
  1.24 KB (-20 B)  build/static/js/main.02386c69.chunk.js
  767 B            build/static/js/runtime-main.873e104b.js

...

Copying files...
Copying files complete.
Copying files complete.
$ 
like image 69
Gopinath Avatar answered Sep 14 '25 12:09

Gopinath


Turns out the solution to this was easy: if you want files in template root, put them in the /template directory.

like image 42
lispquestions Avatar answered Sep 14 '25 13:09

lispquestions