We wrote a ton of internal web tools in our team, using React and Ant.Design. Every time we bootstrap a new web application, we need to bootstrap both frontend code and backend code. And write some glue code between frontend and backend to make them work well together.
I sometimes miss the time I was using PHP. Because I can write all the codes on the server side, then render it out. So I always think that what if we write React code on the server side and just render them?
Then Next.js came out. I really love it. But when I try to integrate Next.js to my Egg application, something stuck me. Because Next.js needs to handle the http context, which is taking an important part in Egg.
So I decided to make a serverside-rendering framework that without taking control of the http context. It’s called Serlina.
In this post, I am gonna tell you how to use Serlina in Egg.
Suppose you have a basic Egg application:
- app
- router.js
- config
- package.json
Now install egg-serlina
:
npm i egg-serlina react react-dom --save
Enable it:
// {app_root}/config/plugin.js
exports.serlina = {
enable: true,
package: 'egg-serlina',
};
You can write your first page now. Just create a folder named client
:
- app_root
- app
+ - client
+ - page
+ - page1.js
Write your page component:
// {app_root}/client/page/page1.js
export default () => {
return <div>Hello Serlina</div>
}
That is! Now you have two way to render this page:
Write a controller and render it manually:
// app/controller/page1.jsmodule.exports = ctx => {
const rendered = await ctx.app.serlina.render('page1')
ctx.body = rendered.string
}
or using auto mapping by the plugin:
// config/config.default.jsexports.serlina = {
map: {
'/page1': 'page1'
}
}
Now, visit http://HOST:PORT/page1 and you will see the page!
Use with Ant.Design
While Serlina support custom Webpack config, you can use Ant.Design easily. We wrote a reusable config helper to make it simpler:
// serlina.config.jsconst { withAntd } = require('antd-serlina-webpack-config')module.exports = {
webpack: withAntd()
}
You can see the whole integrate step in: https://github.com/serlina-community/egg-serlina-example/commit/c484227bd5fe0903f7855b2714d80008294c0007
If you are interested in Serlina, please see:
Serlina full documentations: https://serlina.js.org
egg-serlina: https://github.com/serlina-community/egg-serlina