代码之家  ›  专栏  ›  技术社区  ›  abu abu

React中的条件导入。js

  •  0
  • abu abu  · 技术社区  · 4 年前

    我需要有条件地进口。我使用下面的代码,并得到错误。

    if (window.location.hostname == 'sellbutton') {
      import serviceToUSe from '../public/service/sellbutton.com.json';
    } else {
      import serviceToUSe from '../public/service/default.json';
    }
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   Dharman chazomaticus    4 年前

    我认为您需要首先声明一个空位置,以便在使用后有条件地存储数据 require 而不是导入:

    //This might an object {} or array [] depending on your json data structure. 
    var serviceToUSe = {};
    
    if (window.location.hostname == 'sellbutton') {
      serviceToUSe = require('../public/service/sellbutton.com.json');
    } else {
      serviceToUSe = require('../public/service/default.json');
    }