如何在Create React App SPA中有选择地呈现代码?

戴夫·萨格

在我的React应用程序(使用Create React App cli构建,未弹出)中进行了设置,因此,如果REACT_APP_API_URL未定义,则使用模拟数据。

我通过fakeFetchredux-api-middlewareala提供一个函数来做到这一点

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Create React App中删除无效代码

部署到Heroku时如何在没有create-react-app的React应用中设置代理

如何在create-react-app上使用'/'阻止路由

如何在Create React App中不显示警告

如何在Create-React-App中实现MobX?

如何在create-react-app中隐藏API密钥?

如何在create-react-app中使用CSS模块?

如何在Create React App中运行eslint

如何在 create-react-app 中使用 scss 文件?

如何在加载问题上修复 Create React App FOUC

如何在Create React App中使用Scss变量?

如何在 create-react-app 项目上设置 babel?

create-react-app 工具如何在没有 babel 或任何构建工具的情况下工作?

如何在用于 React Native Navigation 的 Stack Navigator 中有条件地呈现标题?

create-react-app:如何在 React 渲染之前加载 html

如何在 React 中使用 Tailwind CSS 来配置 Create React App?

如何在create-react-app中设置babel-plugin-react-css-modules?

create-react-app有什么缺点?

create-react-app在生产中显示我的所有代码,如何将其隐藏?

如何在快速后端 server.js 文件中设置一些值并在 create-react-app 代码中使用它?

React默认的create-react-app App组件呈现两次

如何使用Create React App实现skipWaiting?

如何在Internet Explorer 10或更高版本中使用Create-React-App

如何在基于Create-React-App的应用程序中配置Workbox?

如何在create-react-app上调试开玩笑的单元测试?

如何在基于create-react-app的项目中添加字体?

如何在create-react-app中将`src`文件夹更改为其他内容

如何在使用create-react-app创建的应用中设置环境变量?

如何在不弹出的情况下将CopyWebpackPlugin添加到create-react-app?