How to provide `babel-preset-react-app` env variables?

不羁的心 提交于 2019-12-11 02:46:37

问题


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:


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.



来源:https://stackoverflow.com/questions/50194243/how-to-provide-babel-preset-react-app-env-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!