I am working on an App which connects create-react-app with an express server( using server rendering). I am referring this tutorial for it.To render the file from server, the code is
bootstrap.js
require('ignore-styles');
require('babel-register')({
ignore:[/(node-modules)/],
presets:['es2015','react-app']
});
require('./index');
index.js
import express from 'express';
// we'll talk about this in a minute:
import serverRenderer from './middleware/renderer';
const PORT = 3000;
const path = require('path');
// initialize the application and create the routes
const app = express();
const router = express.Router();
// root (/) should always serve our server rendered page
router.use('^/$', serverRenderer);
// other static resources should just be served as they are
router.use(express.static(
path.resolve(__dirname, '..', 'build'),
{ maxAge: '30d' },
));
// tell the app to use the above rules
app.use(router);
// start the app
app.listen(PORT, (error) => {
if (error) {
return console.log('something bad happened', error);
}
console.log("listening on " + PORT + "...");
});
While running the command
node bootstrap.js
I am getting error that
Error: Using
babel-preset-react-app
requires that you specifyNODE_ENV
orBABEL_ENV
environment variables. Valid values are "development", "test", and "production".
There are a few options here. I will describe the most easy options.
The most easy one is to run your node bootstrap.js like this:
But that is just too long to remember every time, so you can use package.json scripts.
If you open up your package.json file, you should see a scripts section (if not, see the doc). In that scripts section you can create your own scripts.
I mostly use 2 scripts, one for development and one for production. So in your case something like:
Now you can run your node app like this:
In development
node run start
ornode start
(because node start is an alias for node run start)and in production
node run serve
(no shorthands here)If you still think your package.json becomes too large, you can abstract that away to some .js files. And change your scripts accordingly to something like:
In those script files you can define both of those environment variables before running your app.