如何搭建一个基于 Egg + Webpack + Vue 的服务端渲染工程项目呢?
项目你可以通过 easywebpack-cli 直接初始化即可完成或者clone egg-vue-webpack-boilerplate。下面说明一下从零如何搭建一个Egg + Webpack + Vue 的服务端渲染工程项目。
- 通过 egg-init 初始化 egg 项目
egg-init egg-vue-ssr
// choose Simple egg app
- 安装 easywebpack-vue 和 egg-webpack
npm i easywebpack-vue --save-dev
npm i egg-webpack --save-dev
- 安装 egg-view-vue 和 egg-view-vue-ssr
npm i egg-view-vue --save
npm i egg-view-vue-ssr --save
- 添加配置
在 ${app_root}/config/plugin.local.js 添加如下配置
exports.webpack = {
enable: true,
package: ‘egg-webpack‘
};
exports.webpackvue = {
enable: true,
package: ‘egg-webpack-vue‘
};
- 在 ${app_root}/config/config.local.js 添加如下配置
const EasyWebpack = require(‘easywebpack-vue‘);
// 用于本地开发时,读取 Webpack 配置,然后构建
exports.webpack = {
webpackConfigList: EasyWebpack.getWebpackConfig()
};
- 配置 ${app_root}/webpack.config.js
‘use strict‘;
const path = require(‘path‘);
module.exports = {
egg: true,
framework: ‘vue‘,
entry: {
include: [‘app/web/page‘, { ‘app/app‘: ‘app/web/page/app/app.js?loader=false‘ }],
exclude: [‘app/web/page/[a-z]+/component‘, ‘app/web/page/test‘, ‘app/web/page/html‘, ‘app/web/page/app‘],
loader: {
client: ‘app/web/framework/vue/entry/client-loader.js‘,
server: ‘app/web/framework/vue/entry/server-loader.js‘,
}
},
alias: {
server: ‘app/web/framework/vue/entry/server.js‘,
client: ‘app/web/framework/vue/entry/client.js‘,
app: ‘app/web/framework/vue/app.js‘,
asset: ‘app/web/asset‘,
component: ‘app/web/component‘,
framework: ‘app/web/framework‘,
store: ‘app/web/store‘
},
loaders: {
eslint: false,
less: false, // 没有使用, 禁用可以减少npm install安装时间
stylus: false // 没有使用, 禁用可以减少npm install安装时间
},
plugins: {
provide: false,
define: {
args() { // 支持函数, 这里仅做演示测试,isNode无实际作用
return {
isNode: this.ssr
};
}
},
commonsChunk: {
args: {
minChunks: 5
}
},
uglifyJs: {
args: {
compress: {
warnings: false
}
}
}
}
};
- 本地运行
node index.js 或 npm start
- Webpack 编译文件到磁盘
// 首先安装 easywebpack-cli 命令行工具
npm i easywebpack-cli -g
// Webpack 编译文件到磁盘
easywebpck build dev/test/prod
项目开发
服务端渲染
在app/web/page 目录下面创建 home 目录, home.vue 文件, Webpack自动根据 .vue 文件创建entry入口, 具体实现请见 webpack.config.js
- home.vue 编写界面逻辑, 根元素为layout(自定义组件, 全局注册, 统一的html, meta, header, body)
<template>
<layout title="基于egg-vue-webpack-dev和egg-view-vue插件的工程示例项目" description="vue server side render" keywords="egg, vue, webpack, server side render">
{{message}}
</layout>
</template>
<style>
@import "home.css";
</style>
<script type="text/babel">
export default {
components: {
},
computed: {
},
methods: {
},
mounted() {
}
}
</script>
- 创建controller文件home.js
exports.index = function* (ctx) {
yield ctx.render(‘home/home.js‘, { message: ‘vue server side render!‘ });
};
- 添加路由配置
app.get(‘/home‘, app.controller.home.home.index);
前端渲染
- 创建controller文件home.js
exports.client = function* (ctx) {
yield ctx.renderClient(‘home/home.js‘, { message: ‘vue server side render!‘ });
};
- 添加路由配置
app.get(‘/client‘, app.controller.home.home.client);
原文地址:https://www.cnblogs.com/haojf/p/10774825.html
时间: 2024-10-07 17:44:52