In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the example analysis of Egg.js customization business Web framework extension, the content is very detailed, interested friends can refer to, hope to be helpful to you.
What do you think of when it comes to Node.js Web development?
The first is the framework selection: Express, Koa, NestJS, EggJS, etc., you need to choose one suitable for the team from a variety of frameworks.
After the framework is selected, you need to initialize the project, install dependencies, plug-ins, middleware, and configure common libraries.
If you do a new project again, you have to initialize it all over again. A better one can encapsulate a skeleton and generate a new project from the skeleton, over and over again.
Let's think about what is the flaw in doing so.
If there is no skeleton, the technical selection of team members is inconsistent and blooms everywhere; there is a learning cost for each new project maintenance.
Even if there is a skeleton, some upgrades will require a unified upgrade of each project, which will lead to disunity.
Based on the above reasons, the solution we consider is to encapsulate a unified business framework based on the general framework and sink the common functions used by the team into the business framework.
Business framework encapsulation framework selection
The mainstream Web framework selection is mainly divided into two major genres, Express-based and Koa-based, both of which are built by the same team. The differences in design ideas between Express and Koa are as follows:
Express itself has a lot of built-in middleware with high integration, easy to use and easy to use.
Koa uses a compact kernel, which is lighter and requires users to make technical choices to build building blocks on demand.
Based on the differences in the above design ideas, and based on the consideration of flexible configuration, the author chooses the school based on Koa. But they are all too low-level and need to be customized to build an enterprise-level business framework.
What is Egg.js?
Based on the above demands, the editor finally chose Egg.js.
Egg.js address: https://eggjs.org/zh-cn/
Egg.js is an open source Koa2-based enterprise Node.JS framework based on Ali, and its core design is to produce more upper-level frameworks based on Egg.js.
A quote from the official website
We know that while enterprise applications pursue standardization and co-building, we also need to consider how to balance the differences between different teams and seek common ground while reserving differences. So instead of choosing the large bazaar model of common community frameworks (integrating functions such as database, template engine, front-end framework, etc.), we focus on providing the core functions of Web development and a set of flexible and extensible plug-in mechanisms. "--official website"
Customized goal
Before we start customizing the business framework, let's set the goals that need to be customized.
Expand Controller, add API success / failure return result function
Set the default template engine to pug
Extend ctx, add util, and use dayjs as a unified date processing library
Coding
If you are not familiar with Egg.js, it is recommended to learn the basic use of Egg.js first.
Framework initialization
Initialize the project with the following command. Where-- type=framework represents the frame skeleton
Villa-framework is the frame name and project folder name
$npm init egg-type=framework villa-framework
The following is the initialized directory
Villa-framework ├── app │ ├── extend │ └── service ├── config │ ├── config.default.js │ └── plugin.js ├── lib │ └── framework.js ├── test │ ├── fixtures │ └── framework.test.js ├── README.md index.js package.json
Among them, app and config directories are basically no different from normal Egg.js applications, but framework.js files are added to expand the application.
/ / lib/framework.js' use strict'; const path = require ('path'); const egg = require (' egg'); const EGG_PATH = Symbol.for ('egg#eggPath'); class Application extends egg.Application {get [EGG_PATH] () {return path.dirname (_ dirname);}} class Agent extends egg.Agent {get [EGG_PATH] () {return path.dirname (_ dirname) }} module.exports = Object.assign (egg, {Application, Agent,}); extend Controller to add the result handling function returned after successful failure / / the following is the code used by Egg.js Controller const Controller = require ('egg'). Controller; / / later modified to const Controller = require (' villa-framework'). Controller
We know from the above source code that Controller comes from the egg object, so we just need to replace it with the Controller we defined.
/ / lib/framework.js adds class Controller extends egg.Controller {ok (data) {this.ctx.body = {success: true, data,};} fail (message, code) {this.ctx.body = {code, message,};}} / / Export adds Controller module.exports = Object.assign (egg, {Application, Agent, Controller,})
In this way, the Controller used by users becomes the Controller of the framework.
Template engine is set to pug
Installation dependency
$npm I-- save egg-view-pug
Start the plug-in
/ / config/plugin.js exports.pug = {enable: true, package: 'egg-view-pug',}
Set up view rendering
/ / config/config.default.js config.view = {mapping: {'.pug': 'pug',},}
In this way, the application framework no longer needs to install and configure separately, and it has the ability of pug template engine by default. Different businesses can load and configure some default plug-ins by default according to their own needs.
Extend ctx.util to use dayjs as a unified date processing library
Installation dependency
$npm I-- save dayjs
Create a new util file in the app folder, add day.js and export
/ / app/util/dayjs.js' use strict'; const dayjs = require ('dayjs'); exports.dayjs = dayjs
Because the new util is not loaded by default, configure a custom loader.
/ / config/config.default.js config.customLoader = {/ / attribute name defined on app app.util util: {directory: 'app/util', / / if it is ctx, use loadToContext inject:' ctx', / / whether to load the framework and plug-in directory loadunit: true,},}
This makes the framework load util by default.
Application creation
Next, let's create the application and use the villa-framework above
Initialize the application $npm init egg-- type=simple villa-project $npm I-- save villa-framework $npm I $npm run dev to modify the upper framework of Egg.js to villa-framework
Add "framework": "villa-framework" to the egg field in package.json
"egg": {"framework": "villa-framework",}, modify controller to test 'use strict'; / / app/controller/home.js const Controller = require (' villa-framework'). Controller; class HomeController extends Controller {async index () {const {dayjs} = this.ctx.util.dayjs; const now = dayjs (). Format ('YYYY-MM-DD HH:mm:ss'); await this.ctx.render (' index.pug', {now}) } renderOk () {this.ok ('hi, egg');} renderFail () {this.fail ('fail', 200);}} module.exports = HomeController; add route' use strict'; / / app/router.js / * @ param {Egg.Application} app-egg application * / module.exports = (app) = > {const {router, controller} = app; router.get ('/', controller.home.index) Router.get ('/ ok', controller.home.renderOk); router.get ('/ fail', controller.home.renderFail);}; add home page template
Create a view folder in app and add index.pug
Html head title hello world body p hello world p # {now}
After startup, you can see the results of the demonstration.
Open http:///127.0.0.1:7001
Open http:///127.0.0.1:7001/ok
Open http:///127.0.0.1:7001/fail
The above demonstrates the basic extension to Egg.js by implementing extension Controller, extending ctx, and adding default plug-ins.
Of course, for a complete business framework, there are still a lot of things missing, but the above provides a way to expand Egg.js, I hope it can provide ideas for you to expand.
This is the end of the sample analysis on the extension of the Web framework for Egg.js customization business. I hope the above content can be helpful to you and learn more. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.