How Egg.js Supports Single Page Application

  1. Enable ejs in config/plugin.js // Other template engines also work
exports.ejs = {
  enable: true,
  package: 'egg-view-ejs',
};
  1. Configure static directory
//config/config.{env}.js

    config.static = {
      prefix: '/',
      dir: path.join(appInfo.baseDir, 'app/view/')
    }
  1. Template configuration
//config/config.{env}.js

 config.view = {
      defaultExt: '.html',
      mapping: {
        '.ejs': 'ejs',
        '.html': 'ejs',
      }
    }
  1. Configure root directory route mapping
// app/router.js

module.exports = app => {
  app.router.get('/', app.controller.home.index);
}
  1. Configure route corresponding controller
// app/controller/home.js

const { Controller } = require('egg');
class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    // render index.html
    await ctx.render('index');
  }
}
module.exports = HomeController;

After completing the above configuration, you can combine with single page application

Article Link:

https://alili.tech/en/archive/nodejs/524de824/

# Latest Articles