Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

vue服务端渲染

我是使用cli脚手架创建vue2.x版本的服务端渲染时碰到的错误,启动后没有错误,但是页面一刷新就这个错误,这个错误说我必须使用import语法,但是这个@babel中的包,我进去看过里面使用的也是 import语法,完全不知道错误原因,有人碰到过么
错误信息如下
image

我在vue.config.js中的配置

// 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 env = process.env;
const isServer = env.RUN_ENV === "server";

module.exports = {
  css: {
    extract: false,
    loaderOptions: {
      scss: {
        additionalData: `@import "@/assets/scss/variables.scss"; @import "@/assets/scss/mixins.scss";`
      }
    }
  },

  devServer: {
    proxy: {
      "/api": {
        target: "http://127.0.0.1:3000",
        changeOrigin: true,
        // pathRewrite: {
        //   "^/api": ""
        // }
      }
    }
  },

  // vue cli中的配置  会使用 webpack-merge 合并到webpack中
  configureWebpack: {
    entry: `./src/entry-${isServer ? 'server' : 'client'}.js`,
    devtool: "source-map",
    target: isServer ? "node" : "web",
    node: isServer ? undefined: false,
    output: {
      libraryTarget: isServer ? "commonjs2" : undefined
    },

    // https://webpack.js.org/configuration/externals/#function
    // https://github.com/liady/webpack-node-externals
    externals: isServer ? nodeExternals({
      // 设置白名单
      allowlist: /.css$/
    }) : undefined,

    optimization: {
      splitChunks:isServer ? false : undefined
    },

    plugins: [
      isServer ? new VueSSRServerPlugin() : new VueSSRClientPlugin()
    ]
  },

  chainWebpack: config => {
    config.module
      .rule("vue")
      .use("vue-loader")
      .tap(options => {
        return merge(options, {
          // https://vue-loader-v14.vuejs.org/zh-cn/options.html#optimizeSSR
          optimization: false
        });
      });
  }
};

服务端启动文件

const express = require('express');
const path = require('path');
const fs = require('fs');
const { createBundleRenderer } = require('vue-server-renderer');
const serverBundle = require('../dist/vue-ssr-server-bundle.json');
const clientManifest = require('../dist/vue-ssr-client-manifest.json');

const app = express();

const template = fs.readFileSync(path.resolve(__dirname,"../public/index.html"),'utf-8');

const renderer = createBundleRenderer(serverBundle, {
  runInNewContext: false,
  template,
  clientManifest
});

app.use(express.static(path.join(__dirname,"../dist")));

app.get("*",(req,res) => {
  res.setHeader("Content-Type", "text/html;chartset-utf-8");
  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) {
      console.log(err,'err');
      return handleError(err);
    }
    console.log(html,'html');
    res.end(html);
  });
});

app.on('error', err => console.log(err));
app.listen(5500,() => {
  console.log("APP running http://127.0.0.1:5500");
});

// entry-server.js


import { createVueApp } from "./main";


export default (context) => {
  // 防止异步组件
  return new Promise((resolve,reject) => {
    const { app, router } = createVueApp();
    // 设置服务器段地址
    router.push(context.url);

    router.onReady(() => {
      const matchedComponents =   router.getMatchedComponents();
      if (!matchedComponents.length) {
        return reject({
          code: 404
        });
      }
      // 返回实例对象
      resolve(app);
    }, reject);
  });
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...