为什么我不应该将 CDN 用于 React 和 Babel?

why should I not use CDN for react & babel?

当我学习 jQuery 和 Bootstrap 时,我们(我的新手学习 Web 框架)被告知 CDN 有很多好处等等。

现在我正在涉足 React/Babel,我们被告知我们应该下载文件并从我们的主机服务器上准备好一切。但我们仍然能够使用 CDN,但仅用于原型设计和开发,不建议用于生产。

我认为使用 CDN 的意义在于节省资金、带宽等

我引用了这些陈述:

巴别塔:Compiling in the browser has a fairly limited use case, so if you are working on a production site you should be precompiling your scripts server-side

React:“The versions above are only meant for development, and are not suitable for production. Minified and optimized production versions of React are available.”(页面底部)

class Button1 extends React.Component {
    constructor(props) {
        super(props);
        this.but = null;
    }
    render() {
        let c = 'mdc-button mdc-button--raised mdc-button--primary mdc-ripple-upgraded';
        let l = e('label', {}, this.props.label);
        let i = iconToggle(this.props.icon);
        this.but = e('button', {className: c, onClick: () => {toggleLights()}}, l, i);
        return e('div', {className: 'myCenter'}, this.but);
    }
}

编辑:

您正在使用 React without JSX

React Without JSX

JSX is not a requirement for using React. Using React without JSX is especially convenient when you don't want to set up compilation in your build environment.

由于您不需要在计算机中编译您的程序,因此您可以毫无问题地包含 react.min.js

Babel 用于将 JSX 转换(编译)为 JavaScript,不建议这样做 按照我下面的说明在浏览器中执行此操作。

网络上的大多数教程都是关于使用 JSX 的,因为它是使用 React 的优势之一。 JSX 是一种语法糖。您可以使用 JSX 编写更少的代码。

试试这个 online Babel compiler 看看 JSX 如何转换为 JavaScript 以及生成了多少代码。

因此,如果您使用 React without JSX,那么使用 CDN 获取 React 库比将其托管在您的服务器中更快。它的工作原理与 jQuery 和 Bootstrap 相同。您不需要包含 Babel,因为您没有使用 JSX。


为什么你不应该使用 CDN 出现在你给出的同一个 Facebook 页面中。

If you prefer to use your own text editor, you can also download this HTML file, edit it, and open it from the local filesystem in your browser. It does a slow runtime code transformation, so don't use it in production.

说清楚,

使用 CDN:

正如 Facebook 所说,它在浏览器中进行了缓慢的运行时代码转换。

那是你的代码没有立即执行。

首先,您的代码应转换为 JavaScript,以便浏览器可以执行它,因为不支持 JSX。

转换为JavaScript后,浏览器执行。

客户端浏览器:

JSX -> JavaScript -> Execute

使用编译(生产版):

当您将 JSX 编译为 JavaScript 时,您可以避免在客户端浏览器中进行运行时代码转换,从而节省大量时间。

通常编译会进行代码优化并生成最终结果代码。

然后你可以缩小它以用短变量名替换长变量,删除注释,删除多余的空行等以减小大小。然后文件被 gzip 压缩并传输到客户端的浏览器。此阶段(缩小和 gzip)减小了大小并节省了带宽并增加了网页呈现时间。

在您的计算机上:

JSX -> JavaScript -> minified JavaScript

客户端浏览器:

JavaScript -> Execute

在编程中,最耗费资源的工作是编译代码。 (执行取决于code/logic)

因此,您正在计算机中执行资源最密集的任务并发送简单的 JavaScript 来执行,这减少了浏览器完成的工作,从而加快了网页加载速度并减少了 CPU 在客户端的浏览器上工作(一些用户可能使用较慢的计算机并且您的网页可能由于使用太多资源而挂起他们的计算机)。