EggJS给Vue单页面提供静态服务

写个小项目时, 不想把Egg和Vue分开部署, 过于麻烦, 所以就研究了下如何让Egg给打包后的Vue提供静态服务
代码地址: https://github.com/klren0312/eggVueSpaTemplate

1.配置EggJS

  1. 在config/plugin.js中开启静态插件
  static: {
    enable: true,
  }
  1. config/config.default.js中配置静态文件存放的文件夹
  config.assets = {
    publicPath: '/public/',
  }
  1. 配置controller
    读取index.html文件, 以html形式返回给请求方
'use strict';

const Controller = require('egg').Controller;
const fs = require('fs')
const path = require('path')

class PageController extends Controller {
  async index () {
    const { ctx } = this
    ctx.response.type = 'html'
    ctx.body = fs.readFileSync(path.resolve(__dirname, '../../public/index.html'))
  }
}

module.exports = PageController;
  1. 配置路由
'use strict'

module.exports = app => {
  const { controller, router } = app
  router.get('/', controller.view.page.index)
}

2.前端配置

  1. 编写复制脚本用于将打包后的文件复制到EggJS项目的public文件夹
const fs = require('fs')
const path = require('path')

/**
 * 复制文件夹
 * @param {*} src 
 * @param {*} dist 
 */
const copyDir = function (src, dest) {
  fs.mkdirSync(dest)
  const files = fs.readdirSync(src)
  for (let i = 0; i < files.length; i++) {
    const current = fs.lstatSync(path.join(src, files[i]))
    if (current.isDirectory()) {
      copyDir(path.join(src, files[i]), path.join(dest, files[i]))
    } else if (current.isSymbolicLink()) {
      const symlink = fs.readlinkSync(path.join(src, files[i]))
      fs.symlinkSync(symlink, path.join(dest, files[i]))
    } else {
      const oldFile = fs.createReadStream(path.join(src, files[i]))
      const newFile = fs.createWriteStream(path.join(dest, files[i]))
      oldFile.pipe(newFile)
    }
  }
}

/**
 * 删除文件夹下所有文件
 * @param {String} path 需要删除的文件夹
 */
function delDir(path) {
  let files = [];
  if (fs.existsSync(path)) {
    files = fs.readdirSync(path);
    files.forEach((file, index) => {
      let curPath = path + "/" + file;
      if (fs.statSync(curPath).isDirectory()) {
        delDir(curPath); //递归删除文件夹
      } else {
        fs.unlinkSync(curPath); //删除文件
      }
    });
    fs.rmdirSync(path);
  }
}


const publicFolder = path.resolve('../app/public')
delDir(publicFolder)
copyDir(path.resolve('dist'), publicFolder)
  1. 配置package.json, 在执行build后, 将文件复制
  "scripts": {
......
    "build": "vue-cli-service build && node copyFolder.js",
......
  },

你可能感兴趣的:(EggJS给Vue单页面提供静态服务)