将 React App 拆分为 2 个独立的部分 [英] Splitting React App to 2 Independent Parts

查看:34
本文介绍了将 React App 拆分为 2 个独立的部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发的应用程序 (Node.js + Express + React + Alt) 面向 2 类人群 - 教师,它是一个具有多条路线的大型应用程序,以及学生,它是一个非常一条路线的小应用.

The app I'm developing (Node.js + Express + React + Alt) is addressed to 2 types of crowds - Teachers, for which it is a large app with multiple routes, and students, for which it is a very small app with a single route.

我想把这两部分完全分开,这样students路由渲染时teachers部分的代码不会被加载.

I want to separate these 2 parts completely, so the code of teachers part won't be loaded when students route is rendered.

我有两个原因:

  1. 缩短学生应用的加载时间 - 当我知道不需要时下载并运行大块 JavaScript 是没有意义的.
  2. 安全方面 - 虽然没有数据泄露,但我还是宁愿对学生隐藏老师使用的代码.

有没有简单的方法可以做到这一点?
我可以使用一个 React 应用程序(和一个 React-Router)吗?

Is there an easy way to do this?
Can I use one React app (And one React-Router)?

感谢您的帮助!

推荐答案

实现这一点的最佳方式是使用 Webpack 功能 代码拆分.这允许您自动将代码分割成块,并仅在需要时加载需要的代码.

The best way to implement this is using the Webpack feature Code Spliting. This allow you automatically split your code in chunks and only load the require code when is needed.

您可以看到 React Router 示例:huge-应用

You can see the React Router example: huge-apps

神奇发生在内部组件(require('./routes/*')),这里他们使用回调方法来获取组件,看起来像这样:

The magic happen in the internal components (require('./routes/*')), here they use the callback method to get the components and look something like this:

export default {
  path: 'nameOfComponent',
  getComponent(location, cb) {
    require.ensure([], (require) => {
      cb(null, require('./components/nameOfComponent'))
    })
  }
}

Require.ensure 被 Webpack 检测到并生成一个包含所有代码及其内部依赖项的新块.

Require.ensure is detected by Webpack and generate a new chunk with all the code and his internal dependencies.

当应用在浏览器中执行时,第一次加载只获取包含路由定义的主块,每个路由组件都是按需加载的(当你改变路由时).

When the application is executed in the browser the first load only get the main chunk with the routes definition, and each router components is loaded on demand (when you change of route).

对我来说,这是最干净的方法.因为您将责任委托给构建系统.在 Webpack 2 中,您可以使用 System.import 而不是 require.ensure,它是更符合 ES6 标准的.

For me, this is the most clean way to do it. Because you delegate the responsibility to the build system. In Webpack 2, you could use System.import instead of require.ensure, and is a more ES6 standard.

这篇关于将 React App 拆分为 2 个独立的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆