Home > Web Front-end > Vue.js > body text

Pre-rendered vue.js application in node and laravel projects

青灯夜游
Release: 2020-09-27 14:04:25
forward
2620 people have browsed it

Pre-rendered vue.js application in node and laravel projects

Server-side rendering is very popular right now. But it's not without its flaws. Pre-rendering is an alternative and may even be better in some cases. Let's take a look at how to pre-render a vue.js application.

In this article, we will explore how prerendering works with vue.js and look at two examples: one a node.js project and one a laravel project.

Recommended related tutorials: node js tutorial, vue.js tutorial, laravel tutorial

##1. Server-side rendering

One disadvantage of JavaScript-based applications is that the page the browser receives from the server is basically empty. The DOM cannot be built until the Javascript is downloaded and run.

This means users have to wait longer before seeing anything. It can also have an impact on SEO if the crawler cannot quickly view the page content.

Server-side rendering (SSR) overcomes this problem by rendering the application on the server so that the client receives the full DOM content when the page is loaded (even before the Javascript is run).

Instead of the browser receiving this from the server:

<head> ... </head>
<body>
<div id="app">
  <!--This is empty, Javascript will populate it later-->
</app>
</body>
Copy after login

Using SSR, it receives a full content page:

<head> ... </head>
<body>
<div id="app">
  <div class="container">
    <h1>Your Server-Side Rendered App</h1>
    <div class="component-1">
      <p>Hello World</p>
      <!--etc etc. This was all rendered on the server-->
</app>
</body>
Copy after login

Server Side Rendering Disadvantages

  • Your application needs to be executable on the server, so you need to design your code to be "universal", that is, it can be browsed Works on server and node servers.


  • Your application will run on every request to the server, adding a traditional load and slow responses. Caching can partially alleviate this situation.

  • You can only do SSR with Node.js. If your main backend is Laravel, Django, etc. then you have to run a node server on the main backend to handle SSR.

2. Pre-rendering

There is another One way to solve the empty page problem: pre-rendering. Using this approach, you run the application before deploying it, capture the page output and replace the HTML file with the captured output.


It's basically the same concept as SSR, except it's pre-deployed in a development environment rather than a live server.

Pre-rendering is typically performed using a headless browser like PhantomJS, and can be integrated into the build flow with Webpack, Gulp, etc.

Advantages of pre-rendering

  • No additional server load, so Faster and cheaper than SSR

  • Simpler production setup and simpler application code, therefore Less error-prone

  • No Node.js production server required

Disadvantages of pre-rendering

  • Not good for pages that display changing data (such as tables) work.

  • #Does not apply to pages with specific user content, such as account pages containing the user's personal information. However, these types of pages are not that important to pre-render anyway; these are our main, frequently used pages that we want to serve fast.

  • #You need to prerender each route individually in your application.

Chart


Client-side rendering onlyServer-side renderingPre-rendering
Production ServerAny/noneNode.js onlyAny/none
Additional server load NoYesNo
Personalized user data? N/AYesNo

三、Vue.js预渲染示例

让我们做一个简单的例子来预渲染一个vue.js应用程序,一次在node.js环境中,一次在laravel环境中。

在这些示例中,我们将使用webpack和pre render spa插件来执行预渲染。

1、Vue和Node

第1步:项目安装

我们将使用vue-cli和webpack-simple模板。

$ vue init webpack-simple vue-node-pr-test
$ cd vue-node-pr-test
$ npm install
Copy after login

我们还需要另外三个模块,后面还有解释。

$ npm install --save-dev http-server html-webpack-plugin prerender-spa-plugin
Copy after login

第2步:在Webpack构建中包含index.html

Webpack -simple模板在Webpack构建输出中不包含index.html文件。然而,当我们预渲染应用程序时,我们需要覆盖我们的索引。因此,让我们将它添加到输出中,以免破坏原始的。

在我们的Webpack .config.js文件中使用html-webpack-plugin将文件包含在Webpack构建中:

var HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);

module.exports.plugins.push(
  new HtmlWebpackPlugin({
    template: &#39;./index.html&#39;,
    inject: false
  }),
);
Copy after login

现在我们改变了我们的Webpack公共路径,因为index.html现在和其他静态资产在同一个文件夹中:

output: {
  path: path.resolve(__dirname, &#39;./dist&#39;),
  filename: &#39;build.js&#39;,
  publicPath: &#39;/&#39;, // was originally &#39;dist&#39;
},
Copy after login

由于路径的变化,我们还需要将index.html中的更改为

第3步:测试Webpack生成版本

现在我们建造:

$ npm run build
Copy after login
Copy after login

我们的dist文件夹应该是这样的:

- dist
-- build.js
-- index.html
-- logo.png
Copy after login

如果我们检查dist/index.html,它会是这样的:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>vue-node-pr-test</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="text/javascript" src="/build.js"></script>
  </body>
</html>
Copy after login

现在我们可以使用http-server并从dist文件夹中提供应用程序。默认情况下,它将运行在localhost:8080:

$ ./node_modules/.bin/http-server ./dist
Copy after login

第4步:预渲染应用程序

现在我们的index.html文件在Webpack构建中,我们可以使用预呈现的HTML更新它。

首先,我们需要在webpack配置中添加prerender-spa-plugin。确保它在html-webpack-plugin之后。

var PrerenderSpaPlugin = require(&#39;prerender-spa-plugin&#39;);

module.exports.plugins.push(
  new PrerenderSpaPlugin(
    path.join(__dirname, &#39;./dist&#39;),
    [ &#39;/&#39; ]
  )
);
Copy after login

PrerenderSpaPlugin的第一个参数是index.html文件的位置,第二个参数是应用程序中的路由列表。在这个例子中,我们只有一条路径。

现在我们再次建造:

$ npm run build
Copy after login
Copy after login

我们的构建将比以前花费更长的时间,因为预渲染插件正在做的事情:

  1. 它创建一个Phantom JS实例并运行应用程序

  2. 获取DOM的快照

  3. 将快照输出到生成文件夹中的HTML文件

它会对每条路径重复这个过程,所以如果你有很多页面,构建应用程序可能需要相当长的时间。

在建立后,我们的dist/index.html现在应该包括所有预渲染的HTML:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>prerender-test</title>
  <style type="text/css">#app {
    font-family: Avenir, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px
  }

  h1, h2 {
    font-weight: 400
  }

  ul {
    list-style-type: none;
    padding: 0
  }

  li {
    display: inline-block;
    margin: 0 10px
  }

  a {
    color: #42b983
  }</style>
</head>
<body>
<div id="app"><img src="/logo.png?82b9c7a5a3f405032b1db71a25f67021">
  <h1></h1>
  <h2>Essential Links</h2>
  <ul>
    <li><a href="https://vuejs.org" target="_blank">Core Docs</a></li>
    <li><a href="https://forum.vuejs.org" target="_blank">Forum</a></li>
    <li><a href="https://gitter.im/vuejs/vue" target="_blank">Gitter Chat</a></li>
    <li><a href="https://twitter.com/vuejs" target="_blank">Twitter</a></li>
  </ul>
  <h2>Ecosystem</h2>
  <ul>
    <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li>
    <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li>
    <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li>
    <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li>
  </ul>
</div>
<script type="text/javascript" src="/build.js"></script>

</body>
</html>
Copy after login

2、Vue 和 Laravel

如果您跳过了Vue和Node示例,我建议您先回去阅读它,因为它包含了对任何常见步骤的更全面的解释。

第1步:项目安装

首先,我们将设置一个新的Laravel项目。

$ laravel new vue-laravel-pr-test
$ cd vue-laravel-pr-test
$ npm install
Copy after login

我们还将增加两个我们需要的NPM模块:

$ npm install --save-dev html-webpack-plugin prerender-spa-plugin
Copy after login

第2步:提供一个普通的HTML文件

默认情况下,Laravel在根URL处提供Blade模板文件。 为了使示例简单,我们将使用我们将在resources / views / index.html创建的以下纯HTML文件替换它

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Laravel</title>
    <link rel="stylesheet" href="/css/app.css">
<body>
<div id="app">
  <example></example>
</div>
<script type="text/javascript" src="/js/app.js"></script>
</body>
</html>
Copy after login

现在,我们需要在根路径上提供该文件,而不是刀片服务器模板。将route /web.php更改为:

Route::get(&#39;/&#39;, function () {
  return File::get(public_path() . &#39;/index.html&#39;);
});
Copy after login

这实际上指向我们的build文件夹,我们很快就会生成它。

第3步:将HTML文件添加到构建中

像在节点示例中一样,我们希望在Webpack构建中包含index.html,以便稍后使用预呈现的HTML覆盖它。

我们需要做一些Webpack配置。在本例中,我使用的是Laravel 5.4,它使用的是Laravel Mix。Mix没有提供本地webpack配置文件,因为它使用自己的默认文件,所以让我们从laravel-mix模块复制一个配置文件:

$ cp ./node_modules/laravel-mix/setup/webpack.config.js .
Copy after login

我们还需要让我们的NPM生产脚本指向这个配置文件,因此编辑包。json,并将生产脚本更改为:

cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js 
--progress --hide-modules --config=webpack.config.js
Copy after login

现在我们将html-webpack-plugin添加到webpack.config.js文件中。把这个添加到文件的底部上面的混合定型部分:

var HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);

module.exports.plugins.push(
  new HtmlWebpackPlugin({
    template: Mix.Paths.root(&#39;resources/views/index.html&#39;),
    inject: false
  });
);
Copy after login

第4步:测试Weback生成版本

现在让我们为生产和服务:

$ npm run production
$ php artisan serve
Copy after login

不过,在运行应用程序时,浏览器中可能会出现错误,因为我们从未为window.Laravel.csrfToken设置值。对于这个简单的例子,注释掉会更快,所以像这样修改resources/assets/js/bootsta .js:

window.axios.defaults.headers.common = {
  &#39;X-Requested-With&#39;: &#39;XMLHttpRequest&#39;
  // &#39;X-CSRF-TOKEN&#39;: window.Laravel.csrfToken;
};
Copy after login

第5步:预渲染应用程序

我们现在需要在webpack配置中使用prerender spa插件来执行预渲染。确保它在HTML网页包插件之后。

var PrerenderSpaPlugin = require(&#39;prerender-spa-plugin&#39;);

module.exports.plugins.push(
  new PrerenderSpaPlugin(
    Mix.output().path,
    [ &#39;/&#39; ]
  )
);
Copy after login

现在我们可以做一个生产构建:

$ npm run production
Copy after login

如果您选中build文件夹,dist/index.html现在应该如下所示,并使用预渲染HTML完成:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Laravel</title>
    <link rel="stylesheet" href="/css/app.css">
</head>
<body>
<div id="app">
    <div>
        <div>
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div>Example Component</div>
                    <div>
                        I&#39;m an example component!
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="/js/app.js"></script>
</body>
</html>
Copy after login

相关推荐:

2020年前端vue面试题大汇总(附答案)

vue教程推荐:2020最新的5个vue.js视频教程精选

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Pre-rendered vue.js application in node and laravel projects. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:vuejsdevelopers.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template