Create Background Jobs for app based on Create-React-App

Created: Feb 27, 2017.

I maintain a single page create-react-app app. I needed to create a daily background job that uses some of the models in my create-react-app. Using the models was difficult because my models use Babel, which usually React loads correctly. But, React does not load Babel for background processes.

The following are steps to create a background process:

1. Install Babel in the Project:

npm install --save babel-cli babel-plugin-transform-class-properties babel-preset-es2015 babel-preset-react babel-register

The following are the current versions of these Babel libs at the time of writing:

  "babel-cli": "^6.23.0",
  "babel-plugin-transform-class-properties": "^6.23.0",
  "babel-preset-es2015": "^6.22.0",
  "babel-preset-react": "^6.23.0",
  "babel-register": "^6.23.0",

2. Store the following in a .babelrc in the create-react-app root project folder:

{
  "presets": [
    "react",
    "es2015"
  ],
  "plugins": [
    "transform-class-properties"
  ]
}

3. At the top of the script file of the background process, after #!/usr/bin/env node, add the following:

require("babel-register");

The require is not assigned to a variable, because we merely want the side effects.

4. Require/Import your app code into your background process script:

var Car = require("../Models/Car").default;