在我的React应用程序(使用Create React App cli构建,未弹出)中进行了设置,因此,如果REACT_APP_API_URL
未定义,则使用模拟数据。
我通过fakeFetch
向redux-api-middleware
ala提供一个函数来做到这一点
import { apiMiddleware as aMl, createMiddleware } from 'redux-api-middleware'
import fakeFetch from 'fixtures/utils/fakeFetch'
const apiMiddleware = apiBase ? aMl : createMiddleware({ fetch: fakeFetch })
// etc... configure the `redux` store with the middleware
开发时很好,但是我希望在实际构建部署时将这些代码与构建完全分离。
有什么办法可以按照以下方式做些什么吗?
<% if process.env.REACT_APP_API_URL %>
import { apiMiddleware } from 'redux-api-middleware'
<% else %>
import { createMiddleware } from 'redux-api-middleware'
import fakeFetch from 'fixtures/utils/fakeFetch'
const apiMiddleware = createMiddleware({ fetch: fakeFetch })
<% endif %>
// etc... configure the `redux` store with the middleware
防止webpack
在生产版本中包含我所有的装置/伪造数据,同时为我提供一种在模拟数据与实时数据之间进行切换的非常简单的方法?
我不想退出该应用程序,但可以使用通过Create React App Configuration Overrides注入的webpack插件。
我想的WebPack代码分裂与动态的进口可能是你最好的选择。这样,您的模拟数据就被捆绑了,但从未发送给客户端(我认为这是这里的主要目标)。
import { apiMiddleware, createMiddleware } from 'redux-api-middleware'
const getMiddleware = async () => {
if (process.env.REACT_APP_API_URL) {
return apiMiddleware;
} else {
// loads bundle over network
const { default: fakeFetch } = await import('fixtures/utils/fakeFetch');
return createMiddleware({ fetch: fakeFetch });
}
}
我知道这并不能直接回答问题,但是从侧面来看,我认为最干净的方法是利用模拟服务器,例如mock-server.com。在开发中,您只需使用中的模拟服务器url process.env.REACT_APP_API_URL
。这样,测试数据就生活在完全不同的环境中,并提供了明确的关注点分离。如果您不想使用第三方工具,则可能还可以创建一个简单的本地Express应用程序,该应用程序仅返回硬编码的JSON。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句