As we all know, Vue SPA single page application is not friendly to SEO, of course, there are corresponding solutions, through searching for information, there are about the following 4 methods. (I have only used the first and third options)
1.Nuxt server rendering application deployment (SSR server rendering)
Server rendering: Vue has requirements for the Vue version and the server. Nodejs environment is required.
Trade-offs using SSR:
Limited by development conditions, browser-specific code can only be used in some lifecycle hook functions. Some external extension libraries may require special processing to run in a server rendering application; The environment and deployment requirements are higher, requiring node.js Server running environment; In the case of high traffic, prepare for the server load and use caching strategies wisely.
Advantage:
Better SEO because search engine crawler crawler tools can view fully rendered pages directly; Faster time-to-content, especially for slow network conditions or slow-running devices.
Deficiencies :(potholes encountered in development)
1. One set of code and two sets of execution environment will cause various problems, such as the server does not have window and document objects, the processing method is to increase the judgment, if it is the client only execute:
if(process.browser){
console.log(window);
}
Copy the code
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
if (process.browser) {
var { WOW } = require('wowjs');
require('wowjs/css/libs/animate.css');
}
Copy the code
2. The Nuxt asyncData method gets data before initializing the page, but only for page component calls:
// Load multiple interfaces concurrently:
async asyncData ({ app, query }) {
let [resA, resB, resC] = await Promise.all([
app.$axios.get('/api/a'),
app.$axios.get('/api/b'),
app.$axios.get('/api/c'),])return {
dataA: resA.data,
dataB: resB.data,
dataC: resC.data,
}
}
Copy the code
3. If you use the V-if syntax, you will probably get this error when deploying online:
Error while initializing app DOMException: Failed to execute ‘appendChild’ on ‘Node’: This node type does not support This method.at object. We [as appendChild] Change v-if to v-show syntax.
2.Nuxt static application deployment
Dynamic routing is ignored when Nuxt.js performs generate static packaging.
-| pages/
---| index.vue
---| users/
-----| _id.vue
Copy the code
To create a static page using dynamic routing, you need to specify the dynamic routing parameter value and configure it in the Routes array.
// nuxt.config.js
module.exports = {
generate: {
routes: [
'/users/1'.'/users/2'.'/users/3']}}Copy the code
Run the package and see the packaged page.
But what if the route dynamic parameter values are dynamic rather than fixed?
Use a function that returns a Promise object type; Use a function whose callback is callback(err, params).
// nuxt.config.js
import axios from 'axios'
export default {
generate: {
routes: function () {
return axios.get('https://my-api/users')
.then((res) = > {
return res.data.map((user) = > {
return {
route: '/users/' + user.id,
payload: user
}
})
})
}
}
}
Copy the code
Now we can access the payload from /users/_id. Vue as follows:
async asyncData ({ params, error, payload }) {
if (payload) return { user: payload }
else return { user: await backend.fetchUser(params.id) }
}
Copy the code
If your dynamic routing has many parameters, such as item details, it may be tens of thousands. You need an interface to return all ids, and then go through the ID when packaging, packaging to the local, if a commodity is modified or removed from the shelf, and then have to re-packaging, packaging is also very slow in the case of a large number, very unrealistic.
Advantage:
Pure static file, fast access; Compared with SSR, it does not involve the server load. Static web pages should not be attacked by hackers, higher security.
Inadequate:
If the dynamic route has many parameters, it is not applicable.
3. Prerender-spa-plugin
If you are only using SEO to improve a few marketing pages (e.g. /, /about, /contact, etc.), then you may need pre-render. Instead of using a Web server to compile HTML dynamically in real time, you use pre-rendering to simply generate static HTML files for specific routes at build time. The advantage is that it’s easier to set up pre-render, and you can treat your front end as a completely static site.
1 $CNPM install prerender-spa-plugin –save vue cli 3 vue.config.js
const PrerenderSPAPlugin = require('prerender-spa-plugin');
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer;
const path = require('path');
module.exports = {
configureWebpack: config= > {
if(process.env.NODE_ENV ! = ='production') return;
return {
plugins: [
new PrerenderSPAPlugin({
// The generated file path can also be the same as webpakc package.
// This is very important!!
// This directory can only have one level. If the directory level is greater than one level, there will be no errors during generation and it will just be stuck during pre-rendering.
staticDir: path.join(__dirname,'dist'),
// Corresponding to its own routing file. For example, if a has parameters, write it as /a/param1.
routes: ['/'.'/product'.'/about'].// This is very important, if this section is not configured, it will not be precompiled
renderer: new Renderer({
inject: {
foo: 'bar'
},
headless: false.// Document.dispatchEvent (new Event('render- Event ')) in main.js.
renderAfterDocumentEvent: 'render-event'})}),]}; }}Copy the code
In main.js add:
new Vue({
router,
render: h= > h(App),
mounted () {
document.dispatchEvent(new Event('render-event'))
}
}).$mount('#app')
Copy the code
Note: The router must have mode: “history”.
HTML folder, for example: about => about/index.html, which contains HTML content.
Advantage:
Small changes, the introduction of a plug-in is done;
Inadequate:
Dynamic routing cannot be used. For projects with only a few pages, packaging can be very slow with hundreds of pages;
4.Phantomjs handles crawlers
Phantomjs is a headless browser based on the WebKit kernel, meaning it has no UI, meaning it’s just a browser, except for clicking, page-turning, and other human-related actions that require programming.
Although “PhantomJS announced the end of development”, SEO processing for Vue has been satisfied.
This solution is actually a bypass mechanism. The principle is to determine whether UA, the source of access, is crawler access through Nginx configuration. If so, the crawler request of search engine will be forwarded to a Node server, and then PhantomJS will parse the complete HTML and return it to the crawler.
To install global PhantomJS, local Express, test:
$phantomjs spider. Js ‘www.baidu.com’ If you see a push of HTML on the command line, congratulations, you’ve conquered Phantomjs.
The effect is the same after startup or after postman is used to add user-agent to Baiduspider in the request header.
The deployment of online
Install node, PM2, PhantomJS, nginx
upstream spider_server {
server localhost:3000;
}
server {
listen 80;
server_name example.com;
location / {
proxy_set_header Host $host:$proxy_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
if ($http_user_agent ~* "Baiduspider|twitterbot|facebookexternalhit|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator|bingbot|Sosospider|Sogou Pic Spider|Googlebot|360Spider") {
proxy_pass http://spider_server;}}}Copy the code
Advantage:
No need to change the project code, according to the original SPA development, compared with the development of SSR cost is not too much; For projects already developed with SPA, this is the only choice.
Inadequate:
Deployment requires node server support. The crawler visit is slower than the web page visit because the crawler is returned to the crawler after the resource load is completed. If a large number of malicious simulated Baidu crawlers are cyclic crawlers, it will cause problems in server load. The solution is to determine whether the IP address visited is the IP address of Baidu official crawlers.
conclusion
If the construction of a large website, such as mall class, do not hesitate to directly on the SSR server rendering, of course, there are corresponding pits for you, the community is more mature, good English, all problems are solved.
If it’s just a personal blog or a company website, you can do all three.