Using Node+vue.js to implement SPA application _node.js

Source: Internet
Author: User

Business requirements

Recently, the company requested the development of the web version of the app, because the app is biased content, and with a chat module, so the general multi-page development is not very suitable, and mainly mobile browsing, loading speed or user experience is more stringent. Researched a lot of frameworks and patterns, and finally made a mess out of it.

Service side

There is no doubt that using node, the use of typescript can be effective in the code at the same time error, strongly typed language to write the server without pressure.

#app. ts only attach important code var Webpack = require (' Webpack ') var webpackdevmiddleware = require (' Webpack-dev-middleware ') var webpack
Config = require ('./webpack.config ') import * as index from "./routes/index";
Import * as Foo from "./routes/foo";

Import * as Bar from "./routes/bar";

var app = Express (); Start the service packaging and listening to the client used files, Webpackdevmiddleware is the development model, he will pack JS in memory, you changed the file, it will be repackaged App.use (Webpackdevmiddleware Webpack

(Webpackconfig), {publicpath: '/__build__/', stats: {colors:true}});
General configuration Items App.set (' views ', __dirname + '/views ');
App.set (' View engine ', ' Ejs ');
App.set (' view options ', {layout:false});
App.use (bodyparser.urlencoded ({extended:true}));
App.use (Bodyparser.json ());
App.use (Methodoverride ());

App.use (express.static (__dirname + '/public ')); var env = Process.env.NODE_ENV | |
' Development ';

if (env = = ' development ') {App.use (ErrorHandler ());}
Routing configuration App.get ('/', index.index);
App.get ('/foo ', foo.index);


App.get ('/bar ', bar.index); App.listen (3000, FunctioN () {console.log ("Demo Express server listening on port%d in%s mode", 3000, app.settings.env);});

 Export var app = app;

Service-Side Render page

#index. ts
Import Express = require ("Express")
import Vueserver = require ("Vue-server")//server-side render Vue plug-in

var Vue = new Vueserver.renderer (); Create a service-side Vue

Export function Index (req:express). Request, Res:express. Response) {

  //Create a component
  var vm = new Vue ({
    Template: '
    <p>this is index!</p>
    '
  }) c11/>//waits for HTML rendering to complete, and then returns to the browser Vueserver.htmlready is Vue-server's own event
  VM. $on (' Vueserver.htmlready ', function (HTML: String) {
    //Here is the Ejs template can be used to set the required data into the window under the global variables to facilitate the client's JS access.
    res.render (' layout ', {server_html:html,server_data: ' Window.cm_data = {name: ' John '} '})
  });



#layout. Ejs all URLs that visit this spa are returned with this page <meta> tag can be set dynamically, as long as the parameters are passed in <! DOCTYPE html>  

Client

#app. js This is/__build__/app.js, you can write with ES6, Webpack will convert the import Vue from './vue.min '//client vue.js import Vuerouter from './vue- Router.min '//vue routing plug-in, with Webpack can be very simple to implement lazy load//lazy load route only access to this route will load JS import Foo from ' Bundle?lazy!.. /.. /components/foo '//cooperate with Webpack's Bundle-loader, easy to implement lazy load import Bar from ' Bundle?lazy!.. /.. /components/bar ' Import Index from ' Bundle?lazy!.. /.. /components/index ' var App = Vue.extend ({}) Vue.use (vuerouter) var router = new Vuerouter ({//here to speak carefully, be sure to set the HTML5 mode, do not However, the inconsistency between the front and back end of the URL will have problems//such as access to the Http://localhost:3000/server definition is to access index.ts this routing file//If not HTML5 mode, after the client JS run will become http:// localhost:3000/#!///In the case of direct browser input Http://localhost:3000/foo server definition is access. TS This routing file//If not HTML5 mode, after client JS run will become http://l
  ocalhost:3000/foo/#!///Set the HTML5 mode, after the loading of JS will not add the #! of these 2 similar anchor characters, to achieve the front and back-end route unification if the user refreshes the browser, the server can render the corresponding page. History:true,//HTML5 mode remove anchor point savescrollposition:true//Remember page scrolling position HTML5 mode applicable})//define routing, as defined by server-side routing path Router.map ({' /': {component:index//front-end routing definition,}, '/foo ': {COmponent:foo}, '/bar ': {Component:bar}})//Start app Router.start (app, ' #app ')

 

Need to improve the place

Front and rear unified template, has found a way to separate the HTML, node end with the Fs.readfilesync method to obtain, the client with Webpack Raw-loader get HTML content

Do not put the source code are nonsense.

Source Address

Https://github.com/yjj5855/node-vue-server-webpack

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.