首页 > 解决方案 > How to set different basepath for images in production and development in React

问题描述

I'm retrieving my images on production as:

src="/dibble_back_end/images/icon.png"

Which then is proxied through my nginx:

location /dibble_back_end {
    proxy_pass http://dibble_back_end:4000;
    rewrite ^/dibble_back_end(.*)$ $1 break;
}

The issue is that on development react server is running in ExpressJS not on ngInx. I'd want to based on environment variable be able to switch between production and development.

e.g.

Dev:

src="localhost:4000/images/icon.png"

Production:

src="/dibble_back_end/images/icon.png"

标签: reactjsexpressnginx

解决方案


您没有提供有关设置的详细信息,但如果您使用的是Create a React App,则可以使用NODE_ENVenvironment variable,例如:

const src = process.env.NODE_ENV === 'production' ? "/dibble_back_end/images/icon.png" : "localhost:4000/images/icon.png"

或者

const basePath = process.env.NODE_ENV === 'production' ? "/dibble_back_end" : "localhost:4000";
const src = `${src}/images/icon.png`;

推荐阅读