vue服务器端渲染_Vue和Cloudflare工作者的服务器端渲染

vue服务器端渲染

A few weeks ago, Scotch.io gave me the push to experiment with Cloudflare Workers and Vue server-side rendering. The experiment was a success, and I’m happy to report the findings.

几个星期前, Scotch.io给我推到实验CloudFlare的工人和Vue公司的服务器端渲染。 该实验是成功的,我很高兴报告这些发现。

In this article, we will publish a full-featured, server-side rendered (SSR) Vue application to Cloudflare Workers. But before we begin, let’s talk about what exactly are Cloudflare Workers, define server-side rendering and compare this setup to a more conventional load-balanced architecture.

在本文中,我们将向Cloudflare Workers发布功能齐全的服务器端渲染(SSR)Vue应用程序。 但是在开始之前,我们先讨论一下Cloudflare Workers到底是什么,定义服务器端渲染,并将此设置与更传统的负载平衡架构进行比较。

Cloudflare工人如何工作? ( How do Cloudflare Workers work? )

Part of a growing edge computing trend, Cloudflare Workers, allows us to push JavaScript code to edge locations in 194 cities across 90 countries. Rather than orchestrating containers or virtual machines, Cloudflare Workers’ deal with isolates. Isolates are lightweight sandboxes for our code that, in turn, are managed by the V8 JavaScript and WebAssembly engine - used by Chromium and Node.js. This model practically eliminates the cold starts and overheads associated with the virtual machine or container model.

作为不断发展的边缘计算趋势的一部分,Cloudflare Workers使我们能够将JavaScript代码推送到90个国家/地区的194个城市的边缘位置。 Cloudflare Workers无需处理容器或虚拟机,而是处理隔离。 隔离是我们代码的轻量级沙箱,这些沙箱又由V8 JavaScript和WebAssembly引擎管理-Chromium和Node.js使用。 该模型实际上消除了与虚拟机或容器模型相关的冷启动和开销。

什么是服务器端渲染? ( What is Server-Side Rendering? )

Quite a lot of things happen when the user navigates to a website. The browser resolves the website domain name, initiates a TCP connection, sends an HTTP request to the webserver, receives the HTTP response.

当用户导航到网站时,会发生很多事情。 浏览器解析网站域名,启动TCP连接,向Web服务器发送HTTP请求,接收HTTP响应。

The HTTP response, if there were no errors, contains the web page’s HTML content. It is at this stage that server-side rendering makes a difference. Without SSR, the browser gets a blank web page and sends out requests for JavaScript, CSS, and other assets. While the user is waiting, the browser receives, parses, and executes the JavaScript code, that in turn, renders the application.

如果没有错误,则HTTP响应包含网页HTML内容。 正是在这个阶段,服务器端渲染才有所作为。 如果没有SSR,浏览器将获得一个空白网页,并发出对JavaScript,CSS和其他资产的请求。 在用户等待期间,浏览器接收,解析并执行JavaScript代码,从而呈现应用程序。

With server-side rendering, the browser receives and renders the full HTML page from the webserver. This avoids the wait time needed to download, parse, and execute the JavaScript code in the browser. When the JavaScript application is loaded, it re(hydrates) or reuses the existing DOM tree and takes over the navigation and rendering.

通过服务器端渲染,浏览器可以从Web服务器接收并渲染完整HTML页面。 这避免了在浏览器中下载,解析和执行JavaScript代码所需的等待时间。 加载JavaScript应用程序后,它将重新(水合)或重用现有的DOM树,并接管导航和渲染。

是否有Cloudflare Workers的替代产品? ( Are there alternatives to Cloudflare Workers? )

The closest alternative to Cloudflare Workers is AWS Lambda@Edge. AWS Lambda@Edge differs in a few key aspects: it features fewer edge locations, and it runs Node.js rather than the V8 engine, which contributes to longer cold start times.

与Cloudflare Workers最接近的替代方法是AWS Lambda @ Edge 。 AWS Lambda @ Edge在几个关键方面有所不同:它具有较少的边缘位置,并且它运行Node.js而不是V8引擎,这导致更长的冷启动时间。

The commonly deployed server-side rendering architecture consists of load balancer(s) distributing incoming traffic to several containerized or virtualized Node.js processes. If we were to match the Cloudflare Workers or AWS Lambda@Edge, we’d have to deploy this setup to every relevant region and availability zone. Cloudflare Workers do all this work for us.

通常部署的服务器端呈现体系结构由负载平衡器组成,这些负载平衡器将传入的流量分配给几个容器化或虚拟化的Node.js进程。 如果要匹配Cloudflare Workers或AWS Lambda @ Edge,则必须将此设置部署到每个相关区域和可用性区域。 Cloudflare工作者为我们完成了所有这些工作。

分步说明 ( Step-by-step instructions )

To publish a server-rendered Vue application to Cloudflare, you’ll need a few things:

要将服务器渲染的Vue应用程序发布到Cloudflare,您需要做一些事情:

  • A Cloudflare account with Workers Unlimited plan, it costs $0.50 / million requests per month, with a minimum charge of $5 / month.

    一个Cloudflare帐户(带有Workers Unlimited计划),每月费用为每百万个请求$ 0.50,最低费用为每月$ 5。
  • A Node.js installation running locally on your machine, and access to the command-line.

    在计算机上本地运行的Node.js安装,并可以访问命令行。

Make sure that you have the latest versions of Vue Cli and Cloudflare Wrangler:

确保您具有最新版本的Vue Cli和Cloudflare Wrangler:

$npm i -g @cloudflare/wrangler @vue/cli

Note the Cloudflare Global API key and Workers Account Id. You can find the Global API key on the bottom of the Api Tokens page. The Workers Account Id is on the right sidebar of the Workers Overview Dashboard ; you may need to scroll down.

请注意Cloudflare全局API密钥和Workers帐户ID。 您可以在Api令牌页面的底部找到Global API密钥。 工人帐户ID位于“工人概述”仪表板的右侧; 您可能需要向下滚动。

Next configure the Workers CLI, it will ask for the account email and the Global API key.

接下来配置Workers CLI,它将询问帐户电子邮件和全局API密钥。

$ wrangler config
Enter Email:
[email protected]
Enter api key:
123456abcdef

Let’s clone the template I prepared. It is a modified Vue CLI project that follows the Server-Side Rendering Guide as closely as possible.

让我们克隆我准备的模板。 它是经过修改的Vue CLI项目,它尽可能遵循《 服务器端渲染指南》 。

$git clone https://github.com/l5x/vue-ssr-cloudflare-workers-template.git
$ cd vue-ssr-cloudflare-workers-template
$ npm install

wrangler.toml is the Cloudflare Workers configuration file. Update the account_id field and run:

wrangler.toml是Cloudflare Workers配置文件。 更新account_id字段并运行:

$npm run publish
...
 Built successfully, built project size is 554 KiB.
 Successfully published your script to https://vue-ssr-cloudflare-workers.YOUR-SUBDOMAIN.workers.dev

And that’s it. You should have a working server-side rendered Vue application with vue-router, vuex, (re)hydration, dynamic imports, critical CSS, and asset injection. Let’s go over the project’s structure and key configuration files.

就是这样。 您应该有一个工作正常的服务器端渲染Vue应用程序,其中包含vue-router,vuex,(重新)水化,动态导入,关键CSS和资产注入。 让我们来看一下项目的结构和关键配置文件。

client.config.js extends the Vue CLI webpack configuration, adds the VueSSRClientPlugin, and removes the HtmlWebpackPlugin and the PreloadWebpackPlugin. The entry for this build is src/entry-client.js.

client.config.js扩展了Vue CLI Webpack配置,添加了VueSSRClientPlugin ,并删除了HtmlWebpackPluginPreloadWebpackPlugin 。 此构建的条目是src/entry-client.js

worker.config.js extends the Vue CLI webpack configuration, removes the HtmlWebpackPlugin, PreloadWebpackPlugin, babel-loader, sets the correct environment variables, enables optimizeSSR in vue-loader options, filters out non-JavaScript assets and concatenates the output into a single file. The entry for this build is src/entry-worker.js.

worker.config.js扩展了Vue CLI Webpack配置,删除了HtmlWebpackPluginPreloadWebpackPluginbabel-loader ,设置了正确的环境变量,在vue-loader选项中启用了optimizeSSR ,过滤掉了非JavaScript资产并将输出连接到一个文件中。 此构建的条目是src/entry-worker.js

vendor/vue-server-renderer/basic.js is a modified Vue Bundle Renderer that works in Cloudflare Workers’ environment. It only supports the renderToString method. See this commit for details.

vendor/vue-server-renderer/basic.js是经过修改的Vue Bundle渲染器,可在Cloudflare Workers的环境中工作。 它仅支持renderToString方法。 有关详细信息,请参见此提交 。

src/entry-worker.js is the entry-point for the Cloudflare Workers. The Worker starts by subscribing to incoming requests i.e., listening to fetch events. For each incoming request, it checks if there are static assets available that match the request URL. If there is a match, Cloudflare Worker Sites responds with the static asset. If the request URL did not match any static assets, the Vue application takes over and matches the request URL to routes defined in src/router/index.js.

src/entry-worker.js是Cloudflare Workers的切入点。 Worker首先订阅传入的请求,即侦听fetch事件。 对于每个传入的请求,它都会检查是否存在与请求URL匹配的静态资产。 如果存在匹配项,则Cloudflare Worker Sites会以静态资产作为响应。 如果请求URL与任何静态资产都不匹配,则Vue应用程序将接管并将请求URL与src/router/index.js定义的路由进行匹配。

接下来 ( Next up )

The setup described in this article should give you a good starting point. Next time we will add caching with Cloudflare Workers KV to this setup. Reach out to me on twitter. I’m happy to help with this or a similar topic.

本文中描述的设置应为您提供一个良好的起点。 下次,我们将使用Cloudflare Workers KV添加缓存到此设置。 在Twitter上与我联系。 我很乐意为您提供有关此主题或类似主题的帮助。

翻译自: https://scotch.io/tutorials/server-side-rendering-with-vue-and-cloudflare-workers

vue服务器端渲染

你可能感兴趣的:(vue,java,web,js,javascript)