1. ホーム
  2. javascript

[解決済み] Reactで設定ファイルを保存し、読み込む方法

2022-08-13 19:08:52

質問

私はreact.jsの初心者です。私はサーバーからデータを取得するコンポーネントを1つ実装し、それを次のように使用しています。

CallEnterprise:function(TenantId){


    fetchData('http://xxx.xxx.xx.xx:8090/Enterprises?TenantId='+TenantId+' &format=json').then(function(enterprises) 
    {
        EnterprisePerspectiveActions.getEnterprise(enterprises);
    }).catch(function()
    {
        alert("There was some issue in API Call please contact Admin");
        //ComponentAppDispatcher.handleViewAction({
        //    actionType: MetaItemConstants.RECEIVE_ERROR,
        //    error: 'There was a problem getting the enterprises'
        //});
    });
},

設定ファイルにURLを保存しておき、テストサーバーや本番サーバーにデプロイしたときに、jsファイルではなく、設定ファイル上でURLを変更する必要がありますが、react.jsで設定ファイルをどのように使用するのかが分かりません。

どなたか、これを実現する方法を教えていただけませんか?

どのように解決するのですか?

webpackでは、環境依存の設定を externals フィールドに置くことができます。 webpack.config.js

externals: {
  'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
    serverUrl: "https://myserver.com"
  } : {
    serverUrl: "http://localhost:8090"
  })
}

もし設定を別のJSONファイルに保存したい場合は、そのファイルをrequireして Config :

externals: {
  'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? require('./config.prod.json') : require('./config.dev.json'))
}

そして、モジュール内では、このコンフィグを利用することができます。

var Config = require('Config')
fetchData(Config.serverUrl + '/Enterprises/...')

Reactの場合。

import Config from 'Config';
axios.get(this.app_url, {
        'headers': Config.headers
        }).then(...);

あなたのユースケースをカバーしているかどうかは分かりませんが、私たちにとってはかなりうまくいっています。