How to provide `babel-preset-react-app` env variab

2019-07-31 17:53发布

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 specify NODE_ENV or BABEL_ENV environment variables. Valid values are "development", "test", and "production".

1条回答
等我变得足够好
2楼-- · 2019-07-31 18:21

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:

NODE_ENV=production BABEL_ENV=production node bootstrap.js

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:

"scripts": {
   "start": "NODE_ENV=development BABEL_ENV=development node bootstrap.js node bootstrap.js",
   "serve": "NODE_ENV=production BABEL_ENV=production node bootstrap.js node bootstrap.js"
}

Now you can run your node app like this:

In development

node run start or node 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:

"scripts": {
   "start": "node scripts/start.js"
   "serve": "node scripts/serve.js"
}

In those script files you can define both of those environment variables before running your app.

查看更多
登录 后发表回答