Add server-side rendering (via bundleRenderer, as this is what the Vue docs recommend, and apparently the only way it does encapsulation)

This commit is contained in:
Steve Sanderson
2017-03-10 10:51:47 +00:00
parent 360688f78b
commit 119b274c19
14 changed files with 117 additions and 51 deletions

View File

@@ -1,11 +1,10 @@
import './css/site.css';
import Vue from 'vue';
import router from './router';
const App = require('./components/app/app.vue.html');
import VueRouter from 'vue-router';
import { routes } from './routes';
Vue.use(VueRouter);
new Vue({
el: 'app',
render: h => h(App, { props: {} }),
router: router
el: '#app-root',
router: new VueRouter({ mode: 'history', routes: routes }),
render: h => h(require('./components/app/app.vue.html'))
});

View File

@@ -0,0 +1,16 @@
import Vue from 'vue';
import VueRouter from 'vue-router';
import { createServerRenderer, RenderResult } from 'aspnet-prerendering';
import { createBundleRenderer } from 'vue-server-renderer';
import { routes } from './routes';
Vue.use(VueRouter);
export default function(context: any) {
const router = new VueRouter({ mode: 'history', routes: routes })
router.push(context.url);
return new Vue({
render: h => h(require('./components/app/app.vue.html')),
router: router
});
}

View File

@@ -0,0 +1,18 @@
import { createServerRenderer, RenderResult } from 'aspnet-prerendering';
import { createBundleRenderer } from 'vue-server-renderer';
const path = require('path');
const bundleRenderer = createBundleRenderer(path.resolve('ClientApp/dist/vue-ssr-bundle.json'), {
template: '<!--vue-ssr-outlet-->'
});
export default createServerRenderer(params => {
return new Promise<RenderResult>((resolve, reject) => {
bundleRenderer.renderToString(params, (error, html) => {
if (error) {
reject(error);
} else {
resolve({ html: html });
}
});
});
});

View File

@@ -1,5 +1,5 @@
<template>
<div class="container-fluid">
<div id='app-root' class="container-fluid">
<div class="row">
<div class="col-sm-3">
<menu-component />
@@ -9,7 +9,6 @@
</div>
</div>
</div>
</template>
<script src="./app.ts"></script>

View File

@@ -33,3 +33,5 @@
</div>
</div>
</template>
<style src="./navmenu.css" />

View File

@@ -1,13 +0,0 @@
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
export default new VueRouter({
mode: 'history',
routes: [
{ path: '/', component: require('./components/home/home.vue.html') },
{ path: '/counter', component: require('./components/counter/counter.vue.html') },
{ path: '/fetchdata', component: require('./components/fetchdata/fetchdata.vue.html') }
]
});

View File

@@ -0,0 +1,5 @@
export const routes = [
{ path: '/', component: require('./components/home/home.vue.html') },
{ path: '/counter', component: require('./components/counter/counter.vue.html') },
{ path: '/fetchdata', component: require('./components/fetchdata/fetchdata.vue.html') }
];

View File

@@ -2,8 +2,10 @@
ViewData["Title"] = "Home Page";
}
<app>Loading...</app>
<div asp-prerender-module="ClientApp/dist/main-server">
<div id='app-root'>Loading...</div>
</div>
@section scripts {
<script src="~/dist/main.js" asp-append-version="true"></script>
<script src="~/dist/main-client.js" asp-append-version="true"></script>
}

View File

@@ -6,9 +6,6 @@
<title>@ViewData["Title"] - WebApplicationBasic</title>
<link rel="stylesheet" href="~/dist/vendor.css" asp-append-version="true" />
<environment names="Staging,Production">
<link rel="stylesheet" href="~/dist/site.css" asp-append-version="true" />
</environment>
</head>
<body>
@RenderBody()

View File

@@ -3,6 +3,7 @@
"version": "0.0.0",
"devDependencies": {
"@types/requirejs": "^2.1.28",
"aspnet-prerendering": "^2.0.3",
"aspnet-webpack": "^1.0.27",
"av-ts": "^0.7.1",
"awesome-typescript-loader": "^3.0.0",
@@ -19,8 +20,11 @@
"vue": "^2.2.2",
"vue-loader": "^11.1.4",
"vue-router": "^2.3.0",
"vue-server-renderer": "^2.2.2",
"vue-ssr-webpack-plugin": "^1.0.2",
"vue-template-compiler": "^2.2.2",
"webpack": "^2.2.0",
"webpack-hot-middleware": "^2.12.2"
"webpack-hot-middleware": "^2.12.2",
"webpack-merge": "^4.0.0"
}
}

View File

@@ -7,7 +7,8 @@
"target": "es5",
"sourceMap": true,
"skipDefaultLibCheck": true,
"types": ["requirejs"]
"types": ["requirejs"],
"lib": ["dom", "es2015"]
},
"exclude": [
"bin",

View File

@@ -2,16 +2,19 @@ const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const VueSSRPlugin = require('vue-ssr-webpack-plugin');
const merge = require('webpack-merge');
const bundleOutputDir = './wwwroot/dist';
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
return [{
// Configuration in common to both client-side and server-side bundles
const sharedConfig = {
stats: { modules: false },
entry: { 'main': './ClientApp/boot-client.ts' },
context: __dirname,
resolve: { extensions: [ '.js', '.ts' ] },
output: {
path: path.join(__dirname, bundleOutputDir),
filename: '[name].js',
publicPath: '/dist/'
},
@@ -25,25 +28,56 @@ module.exports = (env) => {
},
plugins: [
new CheckerPlugin(),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(isDevBuild ? 'development' : 'production')
}
})
]
};
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig, {
entry: { 'main-client': './ClientApp/boot-client.ts' },
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(bundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin('site.css')
new webpack.optimize.UglifyJsPlugin()
])
}];
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
const serverBundlesOutput = {
libraryTarget: 'commonjs2',
path: path.join(__dirname, './ClientApp/dist')
};
const serverBundleConfig = merge(sharedConfig, {
resolve: { mainFields: ['main'] },
entry: { 'main': './ClientApp/boot-server-bundle.ts' },
externals: {},
plugins: [new VueSSRPlugin()],
output: serverBundlesOutput,
target: 'node',
devtool: 'inline-source-map'
});
const vueBundleRendererConfig = merge(sharedConfig, {
entry: { 'main-server': './ClientApp/boot-server.ts' },
output: serverBundlesOutput,
target: 'node'
});
return [clientBundleConfig, serverBundleConfig, vueBundleRendererConfig];
};

View File

@@ -5,17 +5,10 @@ const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
const extractCSS = new ExtractTextPlugin('vendor.css');
return [{
stats: { modules: false },
resolve: {
extensions: [ '.js' ]
},
module: {
rules: [
{ test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' },
{ test: /\.css(\?|$)/, use: extractCSS.extract({ use: 'css-loader' }) }
]
},
resolve: { extensions: [ '.js' ] },
entry: {
vendor: [
'bootstrap',
@@ -27,15 +20,24 @@ module.exports = (env) => {
'vue-router'
],
},
module: {
rules: [
{ test: /\.css(\?|$)/, use: extractCSS.extract({ use: 'css-loader' }) },
{ test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' }
]
},
output: {
path: path.join(__dirname, 'wwwroot', 'dist'),
publicPath: '/dist/',
filename: '[name].js',
library: '[name]_[hash]',
library: '[name]_[hash]'
},
plugins: [
extractCSS,
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
new webpack.DefinePlugin({
'process.env.NODE_ENV': isDevBuild ? '"development"' : '"production"'
}),
new webpack.DllPlugin({
path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'