I am practising Node.js
and decide start from Vue
+ Koa
.
After study Vue
, I think don't really need the template engine anymore. simply response the whole HTML to the front, and using Ajax to request the actions, updating the views by Vue
.
Problem:
context.render('xxx.html')
in Koa
?
or have to implement the IO operation for reading the HTML by myself.That depends, but yeah most people who use a frontend library like Vue or React will leave the view up to the client side and just use the backend for API requests.
You can use koa-views
to get the ctx.render
functionality.
Example usage (I've included koa-router just to have a complete example):
import Koa from 'koa'
import Router frmo 'koa-router'
import views from 'koa-views'
const app = new Koa()
app.use(views(path.join(__dirname, 'views'), { extension: 'pug' }))
And then in your route handlers you can do something like:
router.get('/contacts', async ctx => {
ctx.render('all-contacts') // Renders the `all-contacts.pug` file
})
I would recommend using a dev server which loads up your HTML file, and only using your API server for request handling. You can look into using vue-cli to generate a starter vue project. You will basically want to start the dev server on one port (like 3000) and your API server on another port (3001). The dev server will automatically load up your HTML file and listen to changes in your client. You will just need to set up a proxy
to send all API requests to the API server from your webpack
config.