Read the official vUE documentation, still a little confused. Baidu a bunch of things, finally successfully configured vuE-SSR server prerendering based on VUE-CLI3. If it’s helpful, please give a thumbs-up and suggest using NUxT for better server-side rendering. You need to create your own index.template.html file. This file is in
Article load transfer: lobyte
$vue create vUE – SSR Create a vUE – SSR project.
$CD Vue-SSR After creation, go to the project directory.
Two, the transformation vuE-SSR 1, installation environment
$ npm install vue-server-renderer lodash.merge webpack-node-externals cross-env express –registry=registry.npm.taobao.org –save-dev
2. Create the server. Js file in the root directory. // server.js const express = require(‘express’) const fs = require(‘fs’) const {minify} = require(‘html-minifier’) const path = require(‘path’) const { createBundleRenderer } = require(‘vue-server-renderer’) const app = express() const resolve = file => path.resolve(__dirname, file) const renderer = createBundleRenderer(require(‘./dist/vue-ssr-server-bundle.json’), { runInNewContext: false, template: fs.readFileSync(resolve(‘./index.template.html’), ‘utf-8’), clientManifest: require(‘./dist/vue-ssr-client-manifest.json’), basedir: resolve(‘./dist’) }) app.use(express.static(path.join(__dirname, ‘dist’))) app.get(‘*’, (req, res) => { res.setHeader(‘Content-Type’, ‘text/html’) const handleError = err => { if (err.url) { res.redirect(err.url) } else if (err.code === 404) { res.status(404).send(‘404 | Page Not Found’) } else { res.status(500).send(‘500 | Internal Server Error’) console.error(error during render : ${req.url}) console.error(err.stack) } } const context = { title: ‘document’, url: req.url, keywords: ”, description: ”, } renderer.renderToString(context, (err, html) => { if (err) { return handleError(err) } res.send(minify(html, { collapseWhitespace: true, minifyCSS: true })) }) })
app.on(‘error’, err => console.log(err)) app.listen(8000, () => { console.log(vue ssr started at http://localhost:8000
) })
Create the following two files in the SRC directory: / SRC /entry-client.js/SRC /entry-server.js 1
// entry-client.js import { createApp } from ‘./main’
// Client-specific boot logic…… const { app } = createApp()
$mount(‘# App ‘) 2, entry-server.js
// entry-server.js
import { createApp } from “./main”; Export default Context => {// Since it may be an asynchronous routing hook function or component, we will return a Promise so that the server can wait for everything to be ready before rendering. return new Promise((resolve, reject) => { const { app, router } = createApp();
Router.push (context.url); // Set the location of the router on the server. / / wait until the router may be asynchronous components and hook function resolution through the router. The onReady (() = > {const matchedComponents. = the router getMatchedComponents (); Reject (reject) 404 if (! matchedComponents.length) { return reject({ code: 404 }); } // Promise should resolve the application instance so that it can render resolve(app); }, reject); });Copy the code
}; Create a webpack configuration file in the root directory. Vue-cli3 + configuration of Webpack has been moved to vue.config.js in the root directory. Therefore, create a vue.config.js file in the root directory. // vue.config.js const VueSSRServerPlugin = require(“vue-server-renderer/server-plugin”); const VueSSRClientPlugin = require(“vue-server-renderer/client-plugin”); const nodeExternals = require(“webpack-node-externals”); const merge = require(“lodash.merge”); const TARGET_NODE = process.env.WEBPACK_TARGET === “node”; const target = TARGET_NODE ? “server” : “client”;
Module.exports = {CSS: {extract: false}, configureWebpack: () => ({// point entry to the server/client file of the application: / SRC /entry-${target}.js, // provide source map support for bundle renderer devtool: ‘source-map’, target: TARGET_NODE? “node” : “web”, node: TARGET_NODE ? undefined : false, output: { libraryTarget: TARGET_NODE ? “Commonjs2” : undefined}, / / webpack.js.org/configurati… / / github.com/liady/webpa… // Externalize application dependency modules. Make server builds faster, // and generate smaller bundles. externals: TARGET_NODE ? NodeExternals ({// Do not externalize dependencies that WebPack needs to process. // You can add more file types here. For example, if the *.vue raw file is not processed, // you should also whitelist dependent modules that modify global (e.g. polyfill) whitelist: [/.css$/]}) : undefined, optimization: {splitChunks: false}, plugins: [TARGET_NODE? New VueSSRServerPlugin() : new VueSSRClientPlugin()] }), chainWebpack: config => { config.module .rule(“vue”) .use(“vue-loader”) .tap(options => { merge(options, { optimizeSSR: false }); }); }}; Modify package.json file and add the following code to the scripts property: “build:client”: “vue-cli-service build”, “build:server”: “cross-env WEBPACK_TARGET=node vue-cli-service build –mode server”, “build:win”: “npm run build:server && move dist\vue-ssr-server-bundle.json bundle && npm run build:client && move bundle Dist \vue-ssr-server-bundle.json” modify main.js, router/index.js, store/index.js
// main.js import Vue from “vue”; import App from “./App.vue”; import { createRouter } from “./router”; import { createStore } from “./store”; Vue.config.productionTip = false; export function createApp() { const router = createRouter(); const store = createStore(); Const app = new Vue({router, store, render: h => h(app)}) return {app, router, store}} 2, router/index.js
// router/index.js import Vue from “vue”; import VueRouter from “vue-router”; import Home from “.. /views/Home.vue”;
Vue.use(VueRouter);
const routes = [ { path: “/”, name: “Home”, component: Home }, ]; export function createRouter() { return new VueRouter({ mode: “history”, base: process.env.BASE_URL, routes }); }
3, store/index. Js
// store/index.js import Vue from “vue”; import Vuex from “vuex”;
Vue.use(Vuex); export function createStore() { return new Vuex.Store({ state: {}, mutations: {}, actions: {}, modules: NPM runbuild:win Run command :npmrunbuild:win Run command :npmrunbuild:win Run command :npmrunbuild:win Node server then go to the browser and open http://localhost:8000. If the page content appears, the configuration is successful!
Article reprinted: Le Byte