What is nunzuck.js in the first place? It’s actually a template engine.

So what is a template engine?

A template engine is a component that constructs string output based on template data. For example, the following function is a template engine: Function examResult (data) {return data.name {data.name} 分, [data. Math] {data. Math} {data. Math} {data. }

Nunjucks is a purely JavaScript template engine developed by Mozilla that can be used both in Node and in the browser. However, it mostly runs in Node because there are better template solutions on the browser side, such as the MVVM framework.

If we enter the following data:

examResult({

name: 'Amy',
English: 70,
math: 80,
ranking: 300
Copy the code

});

The template engine replaces the corresponding variables in the template string with the following output:

Amy scored 70 points in English and 80 points in mathematics in the final examination of the first grade, ranking the 300th in the grade.

The most common output of a template engine is to output web pages, or HTML text. Of course, you can also output Text in any format, such as Text, XML, Markdown, and so on.

For template rendering itself, it’s very, very fast, because it’s just strings, pure CPU operation.

The performance problem is mainly in reading the template content from the file. This is an IO operation, and in node.js we know that the worst thing single-threaded JavaScript can tolerate is synchronous IO, but Nunjucks uses synchronous IO to read template files by default.

The good news is that Nunjucks caches the contents of the read file, that is, the template file is read at most once and stored in memory. Subsequent requests will not read the file again, as long as noCache: false is specified.

In a development environment, you can disable the cache so that templates can be reloaded each time for real-time modification. In a production environment, always open the cache so that there are no performance issues.

koa-nunjuck-2

There is also koA-Nunzuck-2, which is similar to the lightweight KOA middleware used in Nunjucks. www.npmjs.com/package/koa…

NPM install –save koa-nunjucks-2

It can be seen from the documentation that he needs to install a dependency

Chokidar – a plug-in that listens for file changes

npm install chokidar

Watch :true in nunjucksConfig after installation

The update will be synchronized